- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to remove vowels from a string using regular expressions in Java?
The simple character class “[ ]” matches all the specified characters in it. The following expression matches the characters except for xyz.
"[xyz]"
Similarly, the following expression matches all the vowels in the given input string.
"([^aeiouAEIOU0-9\W]+)";
Then you can remove the matched characters by replacing them with the empty string “”, using the replaceAll() method.
Example 1
public class RemovingVowels { public static void main( String args[] ) { String input = "Hi welcome to tutorialspoint"; String regex = "[aeiouAEIOU]"; String result = input.replaceAll(regex, ""); System.out.println("Result: "+result); } }
Output
Result: H wlcm t ttrlspnt
Example 2
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main( String args[] ) { Scanner sc = new Scanner(System.in); System.out.println("Enter input string: "); String input = sc.nextLine(); String regex = "[aeiouAEIOU]"; String constants = ""; System.out.println("Input string: \n"+input); //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()) { constants = constants+matcher.group(); matcher.appendReplacement(sb, ""); } matcher.appendTail(sb); System.out.println("Result: \n"+ sb.toString()+constants ); } }
Output
Enter input string: this is a sample text Input string: this is a sample text Result: ths s smpl txtiiaaee
Advertisements