Java RegEx Matcher.groupCount返回0

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

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

我的Matcher一直返回0表示:

  String s="mas"; // this is for testing, comes from a List 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:

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

如果从m.find()检查返回值,则返回truem.group()返回mas ,因此匹配器找到匹配项。

如果您要做的是计算mybooks.get(i).getBody()s出现mybooks.get(i).getBody() ,您可以这样做:

 String s="mas"; // this is for testing, comes from a List int hit=0; Pattern p=Pattern.compile(s,Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(mybooks.get(i).getBody()); while (m.find()) { hit++; } 

然后,如何在不循环的情况下找到字符串中“mas”(或任何其他)单词的数量?

您可以在Apache Commons中使用StringUtils :

 int countMatches = StringUtils.countMatches("quiero mas dinero...", "mas"); 

您可以在regExp中添加括号,然后在您的示例中为“(mas)”。

Blockquote您可以在regExp中添加括号,然后在您的示例中为“(mas)”。 大段引用

这种方式不适合这项任务。 它显示捕获组的数量包含Matcher m的结果。 在这种情况下,即使模式是“(mas)”用于输入文本,如“mas mas”,m.groupcount()显示1 – 一个且只有两个匹配的groop。

因此,第一个响应是正确的,唯一可能的是匹配计数的目的。