0

I saw this post on CodeWars as an answer in java to finding number of vowels in a word:

    public static int getCount(String str) {
        return str.replaceAll("(?i)[^aeiou]", "").length();
    }

}

Howeve I don't undestand the syntax around this part:

    return str.replaceAll("(?i)[^aeiou]", "").length();

I understand it finds the length after doing something to manipulate the string?

  • 1
    Does this answer your question? [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – Brian Feb 17 '21 at 15:28

1 Answers1

2

String's replaceAll method takes a regular expression as the first parameter, and replaces any matches with the second parameter. In this case, it is being given the regular expression (?i)[^aeiou], which matches all non-vowels, and replaces them with "", an empty string. Then it returns the length of the resulting string,.

Thus this is finding the number of vowels by stripping off all non-vowels, and counting how many characters remain.

The regular expression can be broken down like this:

  • (?i) -- a flag indicating that this is case insensitive, so it will match upper and lower case characters alike.
  • [^aeiou] -- matches characters which are not a, e, i, o, or u. (The ^ inverts the matching.)
Roddy of the Frozen Peas
  • 11,100
  • 9
  • 37
  • 73