文档

Java™ 教程
隐藏目录
PatternSyntaxException类的方法
教程: Java基础类
课程: 正则表达式

PatternSyntaxException类的方法

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

以下源代码,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处的悬空元字符(问号)。缺少开括号是罪魁祸首。


上一页:Matcher 类的方法
下一页:Unicode 支持