คลาส PatternSyntaxException แสดง unchecked exception ที่โยนเมื่อมี syntax error ใน regex string มีเมธอดหลัก 4 ตัว:
getDescription()- คำอธิบายข้อผิดพลาดgetIndex()- index ที่ผิดพลาดgetPattern()- regex pattern ที่มีข้อผิดพลาดgetMessage()- ข้อความเต็ม (error, index, pattern, indicator)
ตัวอย่าง: จับข้อผิดพลาด Unclosed Character Class
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[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String");
String input = sc.nextLine();
// Regex ผิด: [ ไม่มี ] ปิด
String regex = "[";
try {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
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: [
อธิบาย
- Regex
[ไม่สมบูรณ์ (ขาด]) Pattern.compile()โยนPatternSyntaxExceptiongetDescription(): "Unclosed character class"getIndex(): 0 (ตำแหน่งของ[)getMessage(): ข้อความเต็มพร้อม pointer^ชี้ตำแหน่งผิดgetPattern(): pattern ที่ผิดคือ[
ข้อผิดพลาดทั่วไปที่ทำให้ PatternSyntaxException
| ข้อผิดพลาด | ตัวอย่าง | แก้ไข |
|---|---|---|
| Unclosed bracket | [abc, (abc | เพิ่ม ], ) |
| Invalid escape | \x (ไม่ใช่ valid escape) | ใช้ \\x หรือ \xHH |
| Invalid range | [z-a] | สลับเป็น [a-z] |
| Dangling metacharacter | *abc, abc| | เพิ่ม operand หรือ escape |
| Invalid quantifier | a{5,3} | สลับเป็น a{3,5} |
| Unclosed \Q | \Qabc | เพิ่ม \E |
Best Practice
- Wrap
Pattern.compile()ใน try-catch เมื่อ regex มาจาก user input - ใช้
Pattern.quote()สำหรับ literal strings - Validate regex ก่อน deploy (unit test)
- Log
getMessage()สำหรับ debugging