How to know the number of possible occurrences found by the group () method of the Matcher class?

8

After the question " Why did the Matcher class not return the number of groups correctly? , it was explained that the groupCount() method actually returns the number of filter groups in the regular expression, and in question" a href="https://en.stackoverflow.com/questions/242446/what-is-difference-of-users-in-the-messages-matches-and-find-da- class-matcher "> What was the difference in use between match () and find () methods of the Matcher class? " I was told two ways to identify occurrences of Regular Expression (ER) in a particular string. p>

Even taking the example of one of these questions, using the group() method I can retrieve the current occurrence in the string, and with a loop and the find() method, I can retrieve all occurrences found in the string: p>

String text = "um2tres4cinco6sete8";

String regex = "[0-9]";

Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);

while(m.find()){
    System.out.println(m.group());
}

The return of this is:

2  
4  
6  
8

that is, find() found 4 occurrences of ER used.

My question is how to identify the number of possible occurrences without having to resort to loops and increments with the find() method. Does the Matcher class or some class related to it have some method that returns that number of occurrences without loops or "workarounds" with iterations or the only way is to increment in a loop only? p>     

asked by anonymous 03.10.2017 / 03:44

1 answer

4

As this SOen answer , the most you will achieve before Java 9 is to create a method or use replaceAll to count with the method String.split

Before Java 9

You can add your class or create a class that contains a static method like:

static int countMatches(Matcher matcher)
{
    int counter = 0;

    while (matcher.find())
      counter++;

    return counter;
}

To use call like this:

Matcher m = p.matcher(text);
System.out.println(countMatches(m));

Or:

Matcher m = p.matcher(text);
System.out.println(SuaClass.countMatches(m));

Or using .replaceAll to count occurrences in the string:

Matcher m = p.matcher(text);
System.out.println(m.replaceAll("
Matcher m = p.matcher(text);
System.out.println(m.results().count());
").split("
static int countMatches(Matcher matcher)
{
    int counter = 0;

    while (matcher.find())
      counter++;

    return counter;
}
", -1).length - 1);
  

Note: public Stream<MatchResult> results​() means "null", meaning that this character will rarely exist in an instance, but there may be exceptions, so you can try alternatives to it.

Java 9

Java 9 has added the Stream<MatchResult>

With it you can count %code% , it should look like this:

Matcher m = p.matcher(text);
System.out.println(countMatches(m));
    
03.10.2017 / 04:00