Java RegEx Matcher.groupCount返回0

Dav*_*mes 9 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();
Run Code Online (Sandbox Code Playgroud)

我一直"mas 0 quiero mas dinero"在控制台上.为什么哦为什么?

Kep*_*pil 8

Matcher.groupCount()的javadoc :

返回此匹配器模式中捕获组的数量.
组0表示按惯例的整个模式.它不包含在此计数中.

如果你检查它的返回值m.find()返回true,并m.group()返回mas,所以匹配器找到匹配.

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

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++;
}
Run Code Online (Sandbox Code Playgroud)