How to count the amount of occurrence of a substring within a string?

10

I have the following return:

  

EXCEPTION, ClassException, EXCEPTION, Exception Message

I'd like to get the number of times the String EXCEPTION appears using Regex .

I used the following code:

Pattern.compile("(EXCEPTION)",Pattern.DOTALL).matcher(aString).groupCount()

But it returns me 1 . Does anyone know what can be done?

Note: I know you can parse and count the amount in a loop .

Is there any better way to address this problem?

    
asked by anonymous 16.01.2014 / 13:47

2 answers

6

Use this:

import org.apache.commons.lang.StringUtils;

public int calcCaracter(String MinhaString, String Char){

   int qtd = StringUtils.countMatches(MinhaString, Char);

   return qtd;

}
    
16.01.2014 / 13:56
5

The method groupCount() returns the number of groups of the expression, which in this case is one.

You need to loop through Matcher to the end of the String, like this:

String aString = "EXCEPTION,ClassException,EXCEPTION,Mensagem de Exceção";
Matcher m = Pattern.compile("(EXCEPTION)",Pattern.DOTALL).matcher(aString);
int quantidade = 0;
while (m.find()) quantidade++;
System.out.println(quantidade); // saída: 2
    
16.01.2014 / 13:57