【问题标题】:simple java regex throwing illegalstateexception [duplicate]简单的java正则表达式抛出非法状态异常[重复]
【发布时间】:2013-08-17 22:19:29
【问题描述】:

我正在尝试进行快速的健全性检查……但它失败了。这是我的代码 -

import java.util.regex.*;

public class Tester {
    public static void main(String[] args) {
        String s = "a";
        Pattern p = Pattern.compile("^(a)$");
        Matcher m = p.matcher(s);
        System.out.println("group 1: " +m.group(1));
    } 
}

我希望看到group 1: a。但相反,我收到了IllegalStateException: no match found,但我不知道为什么。

编辑:我也尝试打印出groupCount(),它说有 1 个。

【问题讨论】:

    标签: java regex illegalstateexception


    【解决方案1】:

    您需要先调用m.find()m.matches() 才能使用m.group

    • find 可用于查找与您的模式匹配的每个子字符串(主要用于有多个匹配项的情况)
    • matches 将检查整个字符串是否与您的模式匹配,因此您甚至不需要在模式中添加 ^$

    我们也可以使用m.lookingAt(),但现在让我们跳过它的描述(你可以在文档中阅读它)。

    【讨论】:

      【解决方案2】:

      在调用 Matcher.group(int) 之前使用 Matcher#matchesMatcher#find

      if (m.find()) {
         System.out.println("group 1: " +m.group(1));
      }
      

      在这种情况下Matcher#find 更合适,因为Matcher#matches 匹配完整的String(使匹配表达式中的锚字符冗余)

      【讨论】:

        【解决方案3】:

        查看javadocs 中的Matcher。您将看到“在成功匹配之前尝试查询它的任何部分都会导致抛出 IllegalStateException”。

        使用if (matcher.find()) {} 包裹您的group(1) 呼叫以解决此问题。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多