Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all captured groups in Java

Tags:

java

regex

I want to match a single word inside brackets(including the brackets), my Regex below is working but it's not returning me all groups.

Here's 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));
}

Also I've tested it in Regex Planet and it seems to work.

It must return 4 groups:

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

But it's returning just it:

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

What's wrong?

like image 378
developer033 Avatar asked Apr 29 '16 16:04

developer033


People also ask

What are capture groups regex?

Advertisements. Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".

What does public boolean lookingAt () method do?

public boolean lookingAt() : Attempts to match the input sequence, starting at the beginning of the region, against the pattern. public boolean find() : Attempts to find the next subsequence of the input sequence that matches the pattern.

How do I reference a capture group in regex?

If your regular expression has named capturing groups, then you should use named backreferences to them in the replacement text. The regex (?' name'group) has one group called “name”. You can reference this group with ${name} in the JGsoft applications, Delphi, .

Does special group and group 0 is included while capturing groups using groupCount?

There is also a special group, group 0, which always represents the entire expression. This group is not included in the total reported by groupCount .


1 Answers

JAVA does not offer fancy global option to find all the matches at once. So, you need while loop here

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++;
   }
}

Ideone Demo

like image 121
rock321987 Avatar answered Oct 25 '22 03:10

rock321987