Java正则表达式学习(六)

12. PatternSyntaxException 类的方法


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



public String getDescription()  :获得错误描述。


public int getIndex() :获得错误索引。


public String getPattern() :获得字符串形式的错误的正则表达式。


public String getMessage() : 获得一个多行的字符串,包括语法错误和错误的索引、错误的正则表达式模式,以及模式内可视化的索引指示。


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

 

package com.fortune.test;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created with IntelliJ IDEA.
 * User: Alan
 * Date: 12-5-28
 * Time: 下午1:46
 */
public class RegexTestHarness2 {

    public static void main(String[] args) {
        Pattern pattern = null;
        Matcher matcher = null;
        Scanner scanner = new Scanner(System.in);
        while (true) {
            try {
                System.out.printf("%nEnter your regex: ");
                pattern = Pattern.compile(scanner.nextLine());
                System.out.printf("Enter input string to search: ");
                matcher = pattern.matcher(scanner.nextLine());
            } catch (PatternSyntaxException pse) {
                System.out.println("There is a problem with the regular expression!");
                System.out.println("The pattern in question is:" + pse.getPattern());
                System.out.println("The description is:" + pse.getDescription());
                System.out.println("The message is: " + pse.getMessage());
                System.out.println("The index is: " + pse.getIndex());
                System.exit(0);
            }
            boolean found = false;
            while (matcher.find()) {
                System.out.printf(
                        "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) {
                System.out.printf("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 处的元字符(?)附近有语法错误。缺少左括号是导致这个错误的最魁祸首。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值