• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting more than one result from regex groups

 
Sam Ingrassia
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to everyone in advance -

I cannot seem to figure out why I wouldnt receive multiple groups back from this match. I would assume I would receive:

[hello]
[john]


instead i am getting:

[hello]
[hello]

It seems like the regex stops after the first match is found, which leads me to believe that it has to do with some sort of flag -




Thanks,

Sam
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So one problem is that you are treating groups incorrectly. For example, from the API for 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.


And then in the API for group(int):
Capturing groups are indexed from left to right, starting at one. Group zero denotes the entire pattern,


So in your for loop, you may have 2 groups, but you start indexing from 0. group(0) isn't included in the groupCount() return value. So if you just want the groups counted from groupCount() you should start the for index at 1, not zero:


But this is only part of the problem. The Regex you are using will only match one group in the String at a time, because you don't give it a pattern where multiple groups are captured. So the code as provided only gives you the first group of the (first) match that is found. This is fine, you probably want that. You just want to loop over the matcher for all possible matches.

So what you want is a method that you can use in a while loop that will loop through all the matches it can find in the input String. You should look through the API for Matcher to see which method you should use.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic