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()
检查返回值,则返回true
, m.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。
因此,第一个响应是正确的,唯一可能的是匹配计数的目的。
- 在Java中你如何随机选择一个字母(az)?
- 只有在第二次尝试后,maven安装抛出“打开zip文件时出错”
- Java – Servlet 3.0中的异步与Servlet 3.1中的NIO
- Eclipse,Subclipse 1.8.2,SVN 1.7.0要求密码每个动作
- 从字节数组创建文件
- 用Jackson反序列化JSON – 为什么JsonMappingException“没有合适的构造函数”?
- Java应用程序使用的资源在终止时是否被释放?
- Spring 4.0.6 with quartz 1.8.6:setCronExpression方法未暴露给CronTriggerBean类
- 为什么Java编译器有时允许取消装箱为空?