我知道有人问过这个问题,但我无法解决
对于有正文的书对象(西类牙语):"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/