Reputation: 807
How do you return only a group that was found to match?
I have this regex:
".*>(\\d+.*)\\s.*\\(.*</|>(\\d+.+)<"
When I run:
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(comparisonString);
if(m.find() == true){
System.out.println(m.group(1));
}
Whenever the second part of the expression is matched (the expression after the 'OR' operator), null is returned. How do I return the matching group whenever the secondary expression (the expression after 'OR') is matched?
Upvotes: 0
Views: 497
Reputation: 245
You need to use capturing groups:
Pattern pattern = Pattern.compile("(regexToMatch1)|(regexToMatch2)");
...
read in stuff here
...
Matcher matcher = pattern.matcher(yourString);
if (matcher.matches()) {
String firstString = matcher.group(1);
String secondString = matcher.group(2);
}
Then just throw away whatever groups you don't want.
good examples here: http://javamex.com/tutorials/regular_expressions/capturing_groups.shtml
Edit: Wait, I don't think I understand what you're asking. Your groups match, but the groups are null? You just need to reference the second group in your matcher.group(#); call.
Upvotes: 2