0

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?

2
  • 3
    You have only one capturing group in your regex, ([1-5]) at the end. Commented Aug 26, 2022 at 9:26
  • 1
    Also note that matcher.group(0) will always be the full match. I.e. the input string. From the javadoc: Group zero denotes the entire pattern, so the expression m.group(0) is equivalent to m.group() Commented Aug 26, 2022 at 9:26

1 Answer 1

4

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));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.