English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to remove vowels from a string using regular expressions in Java?

Simple character class "[]" matches all specified characters. The following expression matches characters other than xyz.

"[xyz]"

Similarly, the following expression matches all vowels in the given input string.

"([^aeiouAEIOU0-9\\W]+)";

Then, you can use an empty string "" to replace the matched characters by using the replaceAll() method.

example1

public class RemovingVowels {
   public static void main(String args[]) {
      String input = "Hi welcome to w3codebox";
      String regex = "[aeiouAEIOU]";
      String result = input.replaceAll(regex, "");
      System.out.println("Result: "+result);
   }
}
Output result
Result: H welcome to the ttrlspnt

example2

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);
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Match the compiled pattern in the string
      Matcher matcher = pattern.matcher(input);
      //Create 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 result
Enter input string:
this is a sample text
Input string:
this is a sample text
Result:
ths s smpl txtiiaaee

You Might Also Like