aspose file tools*
The moose likes Beginning Java and the fly likes Getting more than one result from regex groups Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Getting more than one result from regex groups" Watch "Getting more than one result from regex groups" New topic
Author

Getting more than one result from regex groups

Sam Ingrassia
Greenhorn

Joined: Feb 18, 2009
Posts: 4
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

Joined: Jan 28, 2003
Posts: 3971
    
  17

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.


Steve
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Getting more than one result from regex groups
 
Similar Threads
RegEx Question
Infinite recurssion when using Regex to extract column names from SQL
Parsing text
Need help in understanding greedy, reluctant quantifiers in regular expressions??
regex pattern to exclude certain substrings from matches