Java RegEx Matcher.groupCount returns 0

家住魔仙堡 提交于 2019-12-17 16:35:48

问题


I know this has been asked but I am unable to fix it

For a book object with body (spanish): "quiero mas dinero" (actually quite a bit longer)

My Matcher keeps returning 0 for:

    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();

I keep getting "mas 0 quiero mas dinero" on console. Why oh why?


回答1:


From the javadoc of Matcher.groupCount():

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.

If you check the return value from m.find() it returns true, and m.group() returns mas, so the matcher does find a match.

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++;
}



回答2:


How could I then find the number of "mas" (or any other) words in a string without looping?

You could use StringUtils in Apache Commons:

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



回答3:


You can add parenthesis in the regExp, then it is "(mas)" in your example.




回答4:


You can add parenthesis in the regExp, then it is "(mas)" in your example.

That way is not suitable for this task. It shows number of capturing groups contain result of Matcher m. In this case even if pattern is "(mas)" for input text like "mas mas" m.groupcount() show 1 - one and only groop for both matches.

So first response is correct and the only possible for the purpose of matches counting.



来源:https://stackoverflow.com/questions/12413974/java-regex-matcher-groupcount-returns-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!