Java RegEx Matcher.groupCount返回0 [英] Java RegEx Matcher.groupCount returns 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?
推荐答案
返回此匹配器模式中捕获组的数量。
组零表示按惯例的整个模式。此计数不包括
。
如果从<$ 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屋!