0

Lets say i have some regex = "..(group1)..|..(group2).."

pattern.matcher(regex)
matcher.find()
// how can i access the result?? 
// i dont wanna use matcher.group(1) or matcher.group(2) 
// since i don't really know what will be the result.

As u can see i don't know how to get my result. im looking for something like matcher.getResultedGroup.. Could anyone please explain what should i do?

  • If u have other suggestion to expand my knowledge i'd love to hear..
1
  • Hi Popokoko, is there a reason why this question has no accepted answers? Commented Jun 30, 2012 at 10:06

4 Answers 4

2

You can use a single capturing group, with non capturing groups inside:

((?:group1)|(?:group2)) 
Sign up to request clarification or add additional context in comments.

2 Comments

There is no need to put parantheses around the complete regexp, the actual match of the full regexp is in group 0.
Yes, this example is meaningful as part of a larger expression.
1

Iterate over Matcher.start(groupNum). groupNum that is not 0, but starts at 0 is what you are looking for (assuming that it's your whole expression).

Otherwise include your whole subexpression into a capturing group: ((group1)|(group2)...) and compare the starting indexes of the inner groups to the outer group.

1 Comment

This is what ive been doing.. though it looks pretty wired it does work (but not perfect..) for (int m = 1; m <= matcher.groupCount(); m++) { if (matcher.group(m) != null) { r = matcher.group(m); } }
0

See the Javadoc http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html and http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html

Maybe somthing like this will work:

while(matcher.find()) {
    String groupMatch = matcher.group(groupIndex)
}

matcher.find will try to find all subsequences (substrings) of a string which are matched by your regular expression.

2 Comments

i should have mention im pretty new with regex and it takes a while to understand everything
See my updated comment and the others as well, each of them are good on their own :)
0

You don't need to go into subgroups if you don't want to. The actual match is in group 0: Matcher.group(0) or the equivalent Matcher.group(). Note that you might want to use non-capturing groups to safe resources.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.