【问题标题】:Matcher.group throws IndexOutOfBoundsException ExceptionMatcher.group 抛出 IndexOutOfBoundsException 异常
【发布时间】:2017-06-03 09:17:19
【问题描述】:

我在下面的代码中尝试使用Matcher.group() 打印字符串中的所有匹配项。

public static void main(String[] args) {
        String s = "foo\r\nbar\r\nfoo"
                + "foo, bar\r\nak  = "
                + "foo, bar\r\nak  = "
                + "bar, bar\r\nak  = "
                + "blr05\r\nsdfsdkfhsklfh";
        //System.out.println(s);
        Matcher matcher = Pattern.compile("^ak\\s*=\\s*(\\w+)", Pattern.MULTILINE)
                .matcher(s);
        matcher.find();
        // This one works
        System.out.println("first match " + matcher.group(1));
        // Below 2 lines throws IndexOutOfBoundsException
        System.out.println("second match " + matcher.group(2));
        System.out.println("third match " + matcher.group(3));

    }

以上代码在线程“main”java.lang.IndexOutOfBoundsException 中抛出异常:没有第 2 组异常。

所以我的问题是Matcher.group() 是如何工作的,如您所见,我将有 3 个匹配的字符串,我如何使用group() 打印所有这些字符串。

【问题讨论】:

  • 您可能想要设置断点并检查matcher 的内容、groupfind 的交互方式等。
  • @luk2302 ,我确实使用了调试器,但不知道 groupfind 是如何交互的,

标签: java regex pattern-matching


【解决方案1】:

很明显,你只有一组:

^ak\\s*=\\s*(\\w+)
//          ^----^----------this is the only group 

例如,您必须使用循环:

while(matcher.find()){
    System.out.println("match " + matcher.group());
}

输出

match = foo
match = bar
match = blr05

阅读groups

捕获组

括号将它们之间的正则表达式分组。他们将其中的正则表达式匹配的文本捕获到编号中 可以通过编号的反向引用重用的组。他们允许你 将正则表达式运算符应用于整个分组的正则表达式。

【讨论】:

  • 为什么只有 1 个组?它是如何创建的,我不能创建多个组,以便在不迭代的情况下将它们全部打印出来。
  • 组是在括号之间定义的,所以在你的模式中你只有(\\w+) 所以这意味着你只有一个组@AmitK 明白吗?
【解决方案2】:

您似乎对捕获组以及在您的字符串中找到的与给定模式匹配的数量感到困惑。在您使用的模式中,您只有一个捕获组

^ak\\s*=\\s*(\\w+)

在模式中使用括号标记捕获组。

如果您想根据输入字符串检索模式的每个 匹配,那么您应该使用 while 循环:

while (matcher.find()) {
    System.out.println("entire pattern: " + matcher.group(0));
    System.out.println("first capture group: " + matcher.group(1));
}

Matcher#find() 的每次调用都会将模式应用于输入字符串,从头到尾,并提供任何匹配项。

【讨论】:

  • 非常感谢您的精彩解释 +1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-24
  • 2023-03-28
  • 1970-01-01
  • 2013-05-20
  • 1970-01-01
  • 2011-05-30
  • 1970-01-01
相关资源
最近更新 更多