如何在 Java 中使用正則表示式從字串中移除母音?


簡單的字元類“[ ]”匹配其中所有指定的字元。以下表達式匹配除了 xyz 之外的字元。

"[xyz]"

類似地,以下表達式匹配給定輸入字串中的所有母音。

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

然後,你可以使用 replaceAll() 方法用空字串“”,替換匹配的字元將其移除。

例 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);
   }
}

輸出

Result: H wlcm t ttrlspnt

例 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 );
   }
}

輸出

Enter input string:
this is a sample text
Input string:
this is a sample text
Result:
ths s smpl txtiiaaee

更新於: 2019-11-21

1K+ 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.