gpt4 book ai didi

java - 模式/匹配器 Java,非零组计数但错误检索?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:55:39 24 4
gpt4 key购买 nike

我的 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.");
}

还有 . 是正则表达式中的特殊字符,您可能想要 \\.?

关于java - 模式/匹配器 Java,非零组计数但错误检索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20987784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com