tags:

views:

236

answers:

4

So I have an IP address as a string. I have this regex (\d{1-3})\.(\d{1-3})\.(\d{1-3})\.(\d{1-3}) How do I print the matching groups?

Thanks!

+2  A: 

If you use Pattern and Matcher to do your regex, then you can ask the Matcher for each group using the group(int group) method

So:

Pattern p = Pattern.compile("(\\d{1-3}).(\\d{1-3}).(\\d{1-3}).(\\d{1-3})"); 
Matcher m = p.matcher("127.0.0.1"); 
if (m.matches()) {   
  System.out.print(m.group(1));  
  // m.group(0) is the entire matched item, not the first group.
  // etc... 
}
Mike Cornell
+1  A: 
import java.util.regex.*;
try {
    Pattern regex = Pattern.compile("(\\d\\{1-3\\})\\.(\\d\\{1-3\\})\\.(\\d\\{1-3\\})\\.(\\d\\{1-3\\})");
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
     for (int i = 1; i <= regexMatcher.groupCount(); i++) {
      // matched text: regexMatcher.group(i)
      // match start: regexMatcher.start(i)
      // match end: regexMatcher.end(i)
     }
    } 
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}
Lieven
You shouldn't need to catch PatternSyntaxException if your regex is hardcoded (like it is). If there's an error in the syntax, you'll find it the first time you run the program.
Michael Myers
@mmyers: force of habits I assume, but you are right.
Lieven
A: 

You might find my blog post here useful:

Regular expressions capturing in Java for Perl hackers

damog