Java 如何匹配多个捕获组,但结果不符合预期

Java 如何匹配多个捕获组,但结果不符合预期,java,regex,match,capturing-group,Java,Regex,Match,Capturing Group,我正在努力学习Java正则表达式。我想将几个捕获组(即j(a(va)))与另一个字符串(即这是java。这是ava,这是va)进行匹配。我希望输出为: I found the text "java" starting at index 8 and ending at index 12. I found the text "ava" starting at index 21 and ending at index 24. I found the text "va" starting at

我正在努力学习Java正则表达式。我想将几个捕获组(即
j(a(va))
)与另一个字符串(即
这是java。这是ava,这是va
)进行匹配。我希望输出为:

I found the text "java" starting at index 8 and ending at index 12.
I found the text "ava" starting at index 21 and ending at index 24.    
I found the text "va" starting at index 34 and ending at index 36.
Number of group: 2
但是,IDE仅输出:

I found the text "java" starting at index 8 and ending at index 12.
Number of group: 2
为什么会这样?我有什么遗漏吗

原始代码:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nEnter your regex:");

        Pattern pattern
                = Pattern.compile(br.readLine());

        System.out.println("\nEnter input string to search:");
        Matcher matcher
                = pattern.matcher(br.readLine());

        boolean found = false;
        while (matcher.find()) {
            System.out.format("I found the text"
                    + " \"%s\" starting at "
                    + "index %d and ending at index %d.%n",
                    matcher.group(),
                    matcher.start(),
                    matcher.end());
            found = true;
            System.out.println("Number of group: " + matcher.groupCount());
        }
        if (!found) {
            System.out.println("No match found.");
        }
运行上述代码后,我输入了以下输入:

Enter your regex:
j(a(va))

Enter input string to search:
this is java. this is ava, this is va
和IDE输出:

I found the text "java" starting at index 8 and ending at index 12.
Number of group: 2

您的regexp只匹配整个字符串
java
,与
ava
va
不匹配。当它匹配
java
时,它会将捕获组1设置为
ava
,将捕获组2设置为
va
,但它不会单独匹配这些字符串。生成所需结果的regexp是:

j?(a?(va))
使前面的项成为可选项,因此它将匹配后面没有这些前缀的项


您的regexp只匹配整个字符串
java
,它不匹配
ava
va
。当它匹配
java
时,它会将捕获组1设置为
ava
,将捕获组2设置为
va
,但它不会单独匹配这些字符串。生成所需结果的regexp是:

j?(a?(va))
使前面的项成为可选项,因此它将匹配后面没有这些前缀的项

您需要正则表达式
(j?(a?(va))

您可以看到演示

您需要正则表达式
(j?(a?(va))


您可以看到演示

尝试使用我认为您误解了捕获组的功能。它们没有使regexp的其他部分成为可选的,因此您的regexp只匹配整个字符串
java
。请不要发布从
系统读取的问题。在
中,并对结果进行处理,因为这意味着您可以a)轻松调试代码,以识别从
系统中读取的错误。在
中或b)硬编码字符串。在这两种情况下,这意味着代码不是最小的示例,并且/或者可以很容易地缩小错误的来源。这也意味着需要更多的工作来重现问题。试着使用我想你误解了捕获组的工作。它们没有使regexp的其他部分成为可选的,因此您的regexp只匹配整个字符串
java
。请不要发布从
系统读取的问题。在
中,并对结果进行处理,因为这意味着您可以a)轻松调试代码,以识别从
系统中读取的错误。在
中或b)硬编码字符串。在这两种情况下,这意味着代码不是最小的示例,并且/或者可以很容易地缩小错误的来源。这也意味着需要更多的工作来重现问题。非常感谢您的帮助!!真的很感激!!非常感谢你的帮助!!真的很感激!!