【发布时间】:2012-09-06 23:54:35
【问题描述】:
我知道有人问过这个问题,但我无法解决它
对于带有正文的书籍对象(西班牙语):"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"。为什么哦为什么?
【问题讨论】:
-
您的模式中没有捕获组,因此
.groupCount()返回零。请注意,这不返回找到了多少匹配项。 -
我怎样才能在不循环的情况下找到字符串中“mas”(或任何其他)单词的数量?
-
我不知道标准 Java 中有什么可以让你这样做。循环有什么问题?
int count = 0; for (; m.find(); count++);应该给你你想要的。 -
没什么,我只是觉得有一种方法(仍在学习 java),它总是更容易阅读
-
从 Java 8 开始,您可能会发现使用
Pattern.splitAsStream().count()很有用。