PatternSyntaxException 클래스는 정규식 문자열에 구문 오류가 발생한 경우 throw되는 확인되지 않은 예외를 나타냅니다. 이 클래스에는 세 가지 주요 메서드가 포함되어 있습니다. -
-
getDescription() − 오류에 대한 설명을 반환합니다.
-
getIndex() − 오류 인덱스를 반환합니다.
-
getPattern() − 오류가 있는 정규식 패턴을 반환합니다.
-
getMessage() − 오류, 인덱스, 오류가 있는 정규식 패턴, 패턴의 오류 표시를 결합한 완전한 메시지를 반환합니다.
예시
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class PatternSyntaxExceptionExample {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);String input = sc.nextLine();
//Regular expression to match first digits of a word
String regex = "["; //\\s+
//Compiling the regular expression
try {
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
//Replacing all space characters with single space
String result = matcher.replaceAll(" ");
System.out.print("Text after removing unwanted spaces: \n"+result);
}catch(PatternSyntaxException ex){
System.out.println("Description: "+ex.getDescription());
System.out.println("Index: "+ex.getIndex());
System.out.println("Message: "+ex.getMessage());
System.out.println("Pattern: "+ex.getPattern());
}
}
} 출력
Enter a String this is a [sample text [ Description: Unclosed character class Index: 0 Message: Unclosed character class near index 0 [ ^ Pattern: []