Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern/ Matcher Java, non zero group count but error retrieving?

My matcher.groupCount() is giving me 4 but when I use matcher.group(0), ..., matcher.group(0), it gives me an error.

Following is my code:

Pattern pattern = Pattern.compile("([0-9]+).([0-9]+).([0-9]+).([0-9]+)");
Matcher matcher1, matcher2;

GeoIP[0][0] = (GeoIP[0][0]).trim();
GeoIP[0][1] = (GeoIP[0][1]).trim();

System.out.println(GeoIP[0][0]);
System.out.println(GeoIP[0][1]);

matcher1 = pattern.matcher(GeoIP[0][0]);
matcher2 = pattern.matcher(GeoIP[0][1]);

System.out.println("matcher1.groupCount() = " + matcher1.groupCount());
System.out.println("matcher2.groupCount() = " + matcher2.groupCount());

System.out.println("matcher1.group(0) = " (matcher1.group(0)).toString());

Console:

Exception in thread "main" 1.0.0.0
1.0.0.255
matcher1.groupCount() = 4
matcher2.groupCount() = 4

java.lang.IllegalStateException: No match found
    at java.util.regex.Matcher.group(Unknown Source)
    at filename.main(filename.java:linenumber)

the line number is pointing to

System.out.println("matcher1.group(0) = " (matcher1.group(0)).toString());
like image 210
FailedMathematician Avatar asked Jan 08 '14 05:01

FailedMathematician


2 Answers

groupCount just tells you how many groups are defined in the regular expression. If you want to actually access a result, you have to perform a match first!

  if (matcher1.find()) {
    System.out.println("matcher1.group(0) = " (matcher1.group(0)).toString());
  } else {
    System.out.println("No match.");
  }

Also . is a special character in regex, you probably wanted \\.?

like image 68
Affe Avatar answered Nov 10 '22 17:11

Affe


if I understand it right, you need access to the four bytes that create IP address. Instead of using groups you can try regex that match IP address and then split the found string.

String GeoIPs = "192.168.1.21, 10.16.254.1, 233.255.255.255";
Pattern pattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
Matcher matcher;

matcher = pattern.matcher(GeoIPs);

while (matcher.find()) {
    String match = matcher.group();
    String[] ipParts = match.split("\\.");
    for (String part : ipParts) {
        System.out.print(part + "\t");
    }
    System.out.println();
}

There are some answers regarding Java regex for IP extracting: Extract ip addresses from Strings using regex and regex ip address from string.

like image 2
vitfo Avatar answered Nov 10 '22 18:11

vitfo