Java RegEx Matcher.groupCount返回0 [英] Java RegEx Matcher.groupCount returns 0

查看:215
本文介绍了Java RegEx Matcher.groupCount返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这已经被问到但是我无法修复它

I know this has been asked but I am unable to fix it

对于一个带有身体(西班牙语)的书籍对象:quiero mas dinero(实际上相当长一点)

For a book object with body (spanish): "quiero mas dinero" (actually quite a bit longer)

我的匹配器一直返回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在控制台上。为什么哦为什么?

I keep getting "mas 0 quiero mas dinero" on console. Why oh why?

推荐答案

来自 Matcher.groupCount()


返回此匹配器模式中捕获组的数量。

组零表示按惯例的整个模式。此计数不包括

如果从<$ c $检查返回值c> m.find()它返回 true m.group()返回 mas ,因此匹配器找到匹配项。

If you check the return value from m.find() it returns true, and m.group() returns mas, so the matcher does find a match.

如果您要做的是在 s 的出现次数> mybooks.get(i).getBody(),你可以这样做:

If what you are trying to do is to count the number of occurances of s in mybooks.get(i).getBody(), you can do it like this:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆