PatternSyntaxException是未检查异常,它指示正则表达式模式中的语法错误。PatternSyntaxException类提供以下方法来帮助您确定出了什么问题:

    以下源代码RegexTestHarness2.java,更新了我们的测试工具,以检查格式错误的正则表达式:

    1. import java.io.Console;
    2. import java.util.regex.Pattern;
    3. import java.util.regex.Matcher;
    4. import java.util.regex.PatternSyntaxException;
    5. public class RegexTestHarness2 {
    6. public static void main(String[] args){
    7. Pattern pattern = null;
    8. Matcher matcher = null;
    9. Console console = System.console();
    10. if (console == null) {
    11. System.err.println("No console.");
    12. System.exit(1);
    13. }
    14. while (true) {
    15. try{
    16. pattern =
    17. Pattern.compile(console.readLine("%nEnter your regex: "));
    18. matcher =
    19. pattern.matcher(console.readLine("Enter input string to search: "));
    20. }
    21. catch(PatternSyntaxException pse){
    22. console.format("There is a problem" +
    23. " with the regular expression!%n");
    24. console.format("The pattern in question is: %s%n",
    25. pse.getPattern());
    26. console.format("The description is: %s%n",
    27. pse.getDescription());
    28. console.format("The message is: %s%n",
    29. pse.getMessage());
    30. console.format("The index is: %s%n",
    31. pse.getIndex());
    32. System.exit(0);
    33. }
    34. boolean found = false;
    35. while (matcher.find()) {
    36. console.format("I found the text" +
    37. " \"%s\" starting at " +
    38. "index %d and ending at index %d.%n",
    39. matcher.group(),
    40. matcher.start(),
    41. matcher.end());
    42. found = true;
    43. }
    44. if(!found){
    45. console.format("No match found.%n");
    46. }
    47. }
    48. }
    49. }

    要运行此测试,请输入?i)foo作为正则表达式。该错误是程序员在写标志表达式(?i)时,忘记了左括号的常见情况。这样做将产生以下结果:

    1. Enter your regex: ?i)
    2. There is a problem with the regular expression!
    3. The pattern in question is: ?i)
    4. The description is: Dangling meta character '?'
    5. The message is: Dangling meta character '?' near index 0
    6. ?i)
    7. ^
    8. The index is: 0

    从此输出中,我们可以看到语法错误是在索引0处悬空的元字符(问号)。导致开头括号缺失的原因。