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?
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".
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.
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, .
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With