13.11 PatternSyntaxException类的方法
PatternSyntaxException是不可控异常,指出正则表达式模式中的语法错误。PatternSyntaxException类提供如下方法帮助你判断发生了什么错误:
l public String getDescription()——获得错误描述。
l public int getIndex()——获得错误索引。
l public String getPattern()——获得错误的正则表达式模式。
l public String getMessage()——返回一个多行字符串,其中包含错误语法及其索引的描述、错误的正则表达式模式,以及模式内错误索引的可视指示。
下面的源代码RegexTestHarness2.java更新了我们的测试示例,检查错误的正则表达式:
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位置的不确定的元字符(问号)。缺少前括号是错误的原因。






