本教程是针对JDK 8编写的。本页面中描述的示例和实践不利用后续版本引入的改进,并且可能使用已不再可用的技术。
请参阅Java语言更改,了解Java SE 9及后续版本中更新的语言功能的概述。
请参阅JDK发布说明,了解所有JDK版本的新功能、增强功能以及已删除或弃用选项的信息。
PatternSyntaxException是一个未检查的异常,表示正则表达式模式中的语法错误。 PatternSyntaxException类提供以下方法来帮助您确定出了什么问题:
public String getDescription(): 检索错误的描述。public int getIndex(): 检索错误的索引。public String getPattern(): 检索错误的正则表达式模式。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("无控制台。");
System.exit(1);
}
while (true) {
try{
pattern =
Pattern.compile(console.readLine("%n输入正则表达式:"));
matcher =
pattern.matcher(console.readLine("输入要搜索的字符串:"));
}
catch(PatternSyntaxException pse){
console.format("存在正则表达式的问题!%n");
console.format("有问题的模式是:%s%n",
pse.getPattern());
console.format("描述是:%s%n",
pse.getDescription());
console.format("消息是:%s%n",
pse.getMessage());
console.format("索引是:%s%n",
pse.getIndex());
System.exit(0);
}
boolean found = false;
while (matcher.find()) {
console.format("我找到了文本" +
" \"%s\",开始索引为" +
" %d,结束索引为 %d。%n",
matcher.group(),
matcher.start(),
matcher.end());
found = true;
}
if(!found){
console.format("未找到匹配项。%n");
}
}
}
}
要运行此测试,请将正则表达式输入为?i)foo。这是一种常见的情况,程序员忘记在嵌入式标志表达式(?i)中添加开括号的错误。这样做将产生以下结果:
输入你的正则表达式:?i) 正则表达式存在问题! 有问题的模式是:?i) 描述为:悬空的元字符'?' 消息为:悬空的元字符'?'在索引0附近 ?i) ^ 索引为:0
从这个输出中,我们可以看到语法错误是在索引0处的悬空元字符(问号)。缺少开括号是罪魁祸首。