
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Consonants from a String Using Regular Expressions in Java
The simple character class “[ ]” matches all the specified characters in it. The meta character ^ acts as negation within the above character class i.e. the following expression matches all the characters except b (including spaces and special characters)
"[^b]"
Similarly, the following expression matches all the consonants in the given input string.
"([^aeiouyAEIOUY0-9\W]+)";
Then you can remove the matched characters by replacing them with the empty string “”, using the replaceAll() method.
Example 1
public class RemovingConstants { public static void main( String args[] ) { String input = "Hi welc#ome to t$utori$alspoint"; String regex = "([^aeiouAEIOU0-9\W]+)"; String result = input.replaceAll(regex, ""); System.out.println("Result: "+result); } }
Output
Result: i e#oe o $uoi$aoi
Example 2
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RemovingConsonants { public static void main( String args[] ) { Scanner sc = new Scanner(System.in); System.out.println("Enter input string: "); String input = sc.nextLine(); String regex = "([^aeiouyAEIOUY0-9\W])"; String constants = ""; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(input); //Creating an empty string buffer StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, ""); } matcher.appendTail(sb); System.out.println("Result: \n"+ sb.toString() ); } }
Output
Enter input string: # Hello how are you welcome to Tutorialspoint # Result: # eo o ae you eoe o uoiaoi #
Advertisements