Kernel Pattern / Matcher Java, the number of non-zero groups, but getting errors?

Mine matcher.groupCount()gives me 4, but when I use matcher.group(0), ... matcher.group(0), he gives me an error.

Below 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)

line number indicates

System.out.println("matcher1.group(0) = " (matcher1.group(0)).toString());
+4
source share
2 answers

groupCountjust tells you how many groups are defined in the regular expression. If you want to access the result, first you need to complete the match!

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

Also .a special regular expression character, you probably wanted \\.?

+7
source

, , IP-. , IP-, .

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();
}

Java regex IP: IP- regex ip- .

+1

All Articles