Count Vowels with Regular Expression

Description: Counts the number of vowels in a given string using a Regular Expression pattern matching scheme. It doesn't take into account that sometimes "Y" is considered a vowel in some situations. Requires the java.util.regex package to be imported.
Tested Platform: Java SE 19, Windows 10
Language: Java
public int countVowelsRegex(String str) {
    int count = 0;
    if (str.length() > 0) {
        // Create a pattern that detects vowels.
        Pattern vowelPattern = Pattern.compile("[aeiou]");
        Matcher vowelMatcher = vowelPattern.matcher(str);

        // Look for the next match and if found, add to count and repeat.
        while (vowelMatcher.find()) 
    return count;

Posted: March 20, 2023

Return to the snippets listing