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 7, Windows 7
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()) 
                        count++;
		}
		
		return count;
}

Submitted: October 23, 2012

Return to the snippets listing