java - 如何打印模式不匹配的列号和行号

标签 java regex expression

如何打印正则表达式模式不匹配的列号和行号。

我当前的代码:

 reader = new BufferedReader(new FileReader(credentialPath));

 Pattern pattern = Pattern
                .compile(ApplicationLiterals.CREDENTIALS_URL_REG_EX);
 String line;
 while ((line = reader.readLine()) != null) {
      Matcher matcher = pattern.matcher(line.trim());
      if (matcher.find()) {
            // System.out.println(matcher.group());
            // System.out.println("**" + matcher.start());
            // System.out.println("***" + matcher.end());
            result = true;
            count1++;
       } else {
            // count1++;
            result = false;
            // System.out.println(matcher.group());
            // System.out.println(matcher.start());
            System.out.println("****problem at line number" + count1);
            break;
       }
  }

最佳答案

您收到 IllegalStateException 的原因是 matcher.group()matcher.start()

很明显,如果控件转到 else block ,则意味着 linePattern 不匹配。当没有找到匹配项时,如何尝试打印该匹配项的 startgroup

异常堆栈跟踪将清楚地说明这一点:- 未找到匹配项

如果您看到 docs :-

Throws: IllegalStateException - If no match has yet been attempted, or if the previous match operation failed

在您的情况下,由于匹配失败,它会抛出 IllegalStateException

正如您已经完成的那样,保留 matcher.group()matcher.start() 注释,取消注释 count1++ 和只需打印 count1 即可。它会给你行号。

更新:-

将此作为您的 else block 。

else {
    count1++;
    result = false;
    System.out.println("**This line doesn't match the pattern*** "+line);
    System.out.println("****problem at line number" + count1);
    break;
}

关于java - 如何打印模式不匹配的列号和行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15808251/

相关文章:

c# - 是否可以将字符串用于 LINQ 查询表达式?

java - 哪个更适合异常处理?

java - 如何设置jsch终端模式?

RegEx 未找到所有匹配项

c++ - 将正则表达式转换/编译为 C 代码

regex - 用逗号分隔的多个 ip 的正则表达式

javascript - 正则表达式(字符串比较)

java - 从 org.eclipse.jface.text.Document 获取错误列表

java - 为什么这两个表达式产生相同的值?

C++ 值在常量表达式中不可用