10 PatternSyntaxException 类的方法

优质
小牛编辑
124浏览
2023-12-01

PatternSyntaxException 是未检查异常,指示正则表达式模式中的语法错误。PatternSyntaxException 类提供了下面的一些方法,用于确定在什么地方发生了错误:

下面的源代码(RegexTestHarness2.java[10])更新了测试用具,用于检查不正确的正则表达式:

import java.io.Console; 
import java.util.regex.Pattern; 
import java.util.regex.Matcher; 
import java.util.regex.PatternSyntaxException; 
 
public class RegexTestHarness2 { 
 
    public static void main(String[] args){ 
        Pattern pattern = null; 
        Matcher matcher = null; 
 
        Console console = System.console(); 
        if (console == null) { 
            System.err.println("No console."); 
            System.exit(1); 
        } 
        while (true) { 
            try { 
                pattern = Pattern.compile(console.readLine("%nEnter your regex: ")); 
                matcher = pattern.matcher(console.readLine("Enter input string to search: ")); 
            } catch (PatternSyntaxException pse){ 
                console.format("There is a problem with the regular expression!%n"); 
                console.format("The pattern in question is: %s%n", pse.getPattern()); 
                console.format("The description is: %s%n", pse.getDescription()); 
                console.format("The message is: %s%n", pse.getMessage()); 
                console.format("The index is: %s%n", pse.getIndex()); 
                System.exit(0); 
            } 
            boolean found = false; 
            while (matcher.find()) { 
                console.format("I found the text \"%s\" starting at " + 
                        "index %d and ending at index %d.%n", 
                        matcher.group(), matcher.start(), matcher.end() 
                    ); 
                found = true; 
            } 
            if (!found){ 
                console.format("No match found.%n"); 
            } 
        } 
    } 
}

运行该测试,输入?i)foo作为正则表达式。这是个臆想出来的错误,程序员在使用内嵌标志表达式(?i)时忘记输入左括号了。这样做会产生下面的结果:

Enter your regex: ?i)
There is a problem with the regular expression!
The pattern in question is: ?i)
The description is: Dangling meta character '?'
The message is: Dangling meta character '?' near index 0
?i)
^
The index is: 0

从这个输出中,可以看出在索引 0 处的元字符(?)附近有语法错误。缺少左括号是导致这个错误的最魁祸首。