Get all captured groups in Java

I want to combine one word inside brackets (including brackets), mine Regexworks below, but it does not return me all groups.

Here is my code:

String text = "This_is_a_[sample]_text[notworking]";
Matcher matcher = Pattern.compile("\\[([a-zA-Z_]+)\\]").matcher(text);                                     
if (matcher.find()) {
    for (int i = 0; i <= matcher.groupCount(); i++) {
    System.out.println("------------------------------------");
    System.out.println("Group " + i + ": " + matcher.group(i));
}

I also tested it in Regex Planet and it seems to work.

He should return 4 groups:

------------------------------------
Group 0: [sample]
------------------------------------
Group 1: sample
------------------------------------
Group 2: [notworking]
------------------------------------
Group 3: notworking

But he returns only this:

------------------------------------
Group 0: [sample]
------------------------------------
Group 1: sample

What's wrong?

+4
source share
2 answers

JAVA does not offer a fantastic global option to immediately find all matches. So you need while loophere

int i = 0;
while (matcher.find()) {
   for (int j = 0; j <= matcher.groupCount(); j++) {
      System.out.println("------------------------------------");
      System.out.println("Group " + i + ": " + matcher.group(j));
      i++;
   }
}

Perfect demonstration

+6
source

, . , , . "([A-Za-z]*):([A-Za-z]*)" "-", 1 2.

(= ), 0 ( , , ) 1 ( , ).

find , .

int i = 0;
while (matcher.find()) {
    System.out.println("Match " + i + ": " + matcher.group(1));
    i++;
}
+2

All Articles