PatternSyntaxException lớp đại diện cho một ngoại lệ không được kiểm tra được ném ra trong trường hợp có lỗi cú pháp trong chuỗi regex. Lớp này chứa ba phương thức chính là -
-
getDescription () - Trả về mô tả lỗi.
-
getIndex () - Trả về chỉ số lỗi.
-
getPattern () - Trả về mẫu biểu thức chính quy có lỗi.
-
getMessage () - Trả về thông báo đầy đủ kèm theo lỗi, chỉ mục, mẫu biểu thức chính quy có lỗi, chỉ báo lỗi trong mẫu.
Ví dụ
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());
}
}
} Đầu ra
Enter a String this is a [sample text [ Description: Unclosed character class Index: 0 Message: Unclosed character class near index 0 [ ^ Pattern: [