I have such pattern:

(?m).*\\bkey\b\\s+(\\w+)\\s+(\\w+).* 

and for example, such a text:

 key type value 

When searching with the .find () function, I display all groups:

 for (int i = 0; i < matcher.groupCount(); i++) { System.out.println(matcher.group(i)); } 

but here for some reason it does not display the 'value', the result:

 key type value type 

What can be wrong?

  • And here - key\b - typo? It is necessary for (int i = 0; i <= matcher.groupCount(); i++) - Wiktor Stribiżew
  • yes, typo, ok spasibo) - Akmal Kamalov

1 answer 1

The number of groups returned by groupCount() is the number of exciting groups in the template + integer match.

 String s = "key type value"; Pattern pattern = Pattern.compile("(?m).*\\bkey\\b\\s+(\\w+)\\s+(\\w+).*"); Matcher matcher = pattern.matcher(s); while(matcher.find()) { for (int i = 0; i <= matcher.groupCount(); i++) { // Тут i <= matcher.groupCount() System.out.println(matcher.group(i)); } } 

See java demo .