Java Online Compiler
Example: Count Vowels and Consonants - Regular Expressions in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Count Vowels and Consonants - Regular Expressions import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize Scanner and get input string Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String inputString = scanner.nextLine(); scanner.close(); // Step 2: Convert the string to lowercase to simplify regex patterns String lowerCaseString = inputString.toLowerCase(); // Step 3: Define regex patterns for vowels and consonants // [aeiou] matches any vowel Pattern vowelPattern = Pattern.compile("[aeiou]"); // [a-z&&[^aeiou]] matches any lowercase letter that is not a vowel Pattern consonantPattern = Pattern.compile("[a-z&&[^aeiou]]"); // Step 4: Count vowels Matcher vowelMatcher = vowelPattern.matcher(lowerCaseString); int vowelCount = 0; while (vowelMatcher.find()) { vowelCount++; } // Step 5: Count consonants Matcher consonantMatcher = consonantPattern.matcher(lowerCaseString); int consonantCount = 0; while (consonantMatcher.find()) { consonantCount++; } // Step 6: Print the results System.out.println("Vowels: " + vowelCount); System.out.println("Consonants: " + consonantCount); } }
Output
Clear
ADVERTISEMENTS