File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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

Getting more than one result from regex groups

Sam Ingrassia

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:


instead i am getting:


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 -


Steve Luke

Joined: Jan 28, 2003
Posts: 4181

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.

I agree. Here's the link:
subject: Getting more than one result from regex groups
It's not a secret anymore!