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

Asked

Viewed 3,444 times

10

I have the following return:

EXCEPTION,Classexception,EXCEPTION,

I’d like to take the amount of times that String appears EXCEPTION using Regex.

I used the following code:

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

But the same returns to me 1. Someone knows what can be done?

Note: I know it is possible to perform the parse and count the amount in a loop.

Is there any better way than I mentioned to solve this problem?

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;

}
  • This Stringutils class is of which package?

  • I added in response!

  • Thank you, I used Stringutils.countOccurrencesOf from the org.springframework.util.Stringutils package.

  • Orders!!!

5

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

You need to go through the Matcher until the end of 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
  • 2

    Thank you for the reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.