Get all groups from a regular expression match
807601May 16 2008 — edited May 16 2008Please help me understand how to use Java regular expressions:
I have an expression similar to this:
{noformat}"([^X]+)(X[^X]*)+"{noformat}This should match stuff like "asaasaXdfdfdfXXsdsfd".
How does one access all the matches for the second group (the second groups has a Kleene operator
added so it is not really just one group --- but match.groupCount() is always 2)
Here is roughly the code:
{noformat}java.util.regex.Pattern pattern = {noformat}{noformat}java.util.regex.Pattern.compile({noformat}{noformat}"([^X]+)(X[^X]*)+",{noformat}{noformat}java.util.regex.Pattern.MULTILINE{noformat}{noformat});{noformat}{noformat}java.util.regex.Matcher matcher = pattern.matcher(text);{noformat}{noformat}matcher.find();{noformat}{noformat}int groupcount = matcher.groupCount();{noformat}
Also, without matcher.find() I get an illegalStateException .. which I also get if I use matcher.matches() instead
of matcher.find().
I am obviously missing something here. There is always at least one "X" in the string so shouldn't that pattern always
match the whole string? Since there are often multiple X, shouldnt I get a group for each occurrence of X, followed
by 0 or more other characters?
{noformat}But when I try to match everything by using "^([^X]+)(X[^X]*)+$" I get an "IllegalStateException: No match available" again.{noformat}
What is the correct way to do this?
Edited by: johann_p on May 16, 2008 10:39 AM