Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
模式/匹配器Java,非零组计数,但检索时出错?_Java_Regex_Matcher - Fatal编程技术网

模式/匹配器Java,非零组计数,但检索时出错?

模式/匹配器Java,非零组计数,但检索时出错?,java,regex,matcher,Java,Regex,Matcher,我的matcher.groupCount()给了我4,但是当我使用matcher.group(0),…,matcher.group(0)时,它给了我一个错误 以下是我的代码: 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]

我的
matcher.groupCount()
给了我4,但是当我使用
matcher.group(0)
,…,
matcher.group(0)
时,它给了我一个错误

以下是我的代码:

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());
控制台:

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)
行号指向

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

groupCount
只告诉您正则表达式中定义了多少个组。如果您想实际访问结果,必须先执行匹配

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

另外,
是regex中的一个特殊字符,您可能想要
\.

如果我理解正确,您需要访问创建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();
}
关于IP提取的Java正则表达式,有一些答案: 和