Home > Back-end >  Java Regex Matcher get wrong group count?
Java Regex Matcher get wrong group count?

Time:08-29

My code is

String debug = "1$<$2";
Matcher matcher = Pattern.compile("^[1-5]"   "\\(?\\$[^\\$]*\\$\\)?"   "([1-5])$").matcher(debug);
List<String> matches = new ArrayList<String>();
if (matcher.matches()) {
  for (var i = 0;i< matcher.groupCount();i  ){
    matches.add(matcher.group(i));
  }
}
System.out.println(matcher.groupCount());
System.out.println(matches);

And the group count is only 1.

The matches is 1$<$2.

But actually the result of matcher.group(1) is 2.

How can I get the right group count?

CodePudding user response:

That is because the first group (index 0) is the whole pattern and is not counted. See the javadoc:

public int groupCount()

Returns the number of capturing groups in this matcher's pattern.
Group zero denotes the entire pattern by convention. It is not included in this count.
Any non-negative integer smaller than or equal to the value returned by this method is guaranteed to be a valid group index for this matcher.

So you can change your code to this for example:

for (var i = 1; i <= matcher.groupCount(); i  ){
  matches.add(matcher.group(i));
}
  • Related