Java RegEx Matcher.groupCount 返回 0

标签 java regex matcher

我知道有人问过这个问题,但我无法解决

对于有正文的书对象(西类牙语):"quiero mas dinero"(实际上要长很多)

我的 Matcher 不断返回 0:

    String s="mas"; // this is for testing, comes from a List<String>
    int hit=0;
    Pattern p=Pattern.compile(s,Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(mybooks.get(i).getBody());
    m.find();
    System.out.println(s+"  "+m.groupCount()+"  " +mybooks.get(i).getBody());
    hit+=m.groupCount();

我一直在控制台上收到 "mas 0 quiero mas dinero"。为什么啊为什么?

最佳答案

来自 Matcher.groupCount() 的 javadoc :

Returns the number of capturing groups in this matcher's pattern.
Group zero denotes the entire pattern by convention. It is not included in this count.

如果您检查 m.find() 的返回值,它返回 true,而 m.group() 返回 mas,所以匹配器确实找到了匹配项。

如果你想做的是计算 mybooks.get(i).getBody()s 的出现次数,你可以这样做这个:

String s="mas"; // this is for testing, comes from a List<String>
int hit=0;
Pattern p=Pattern.compile(s,Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(mybooks.get(i).getBody());
while (m.find()) {
    hit++;
}

关于Java RegEx Matcher.groupCount 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12413974/

相关文章:

java - Google Cloud Dataflow 管道中的 NotSerializedException : org. apache.avro.io.DecoderFactory

java - 如何打开 webview 上的每个链接到 chrome 自定义选项卡?

c# - 替换 css 中的大小参数

javascript - 如何用javascript仅替换字符串中最后一次出现的数字?

c# - "Tight"重复键/值匹配

java正则表达式清除mediawiki标记

java - 迭代 HashSet 并在每次迭代中删除多个元素

java - 如何使用 ReJson 在 Redis 中存储复杂的 Json

scala - 如何匹配 ScalaTest 中的实例类型

java - 获得独特的正则表达式匹配器结果(不使用 map 或列表)