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


簡單的字元類“[ ]”匹配其中的所有指定字元。元字元^在此字元類中充當否定,即以下表達式匹配除 b(包括空格和特殊字元)以外的所有字元

"[^b]"

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

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

然後,你可以使用 replaceAll() 方法用空字串“”,替換匹配的字元,從而刪除它們。

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

輸出

Result: i e#oe o $uoi$aoi

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

輸出

Enter input string:
# Hello how are you welcome to Tutorialspoint #
Result:
# eo o ae you eoe o uoiaoi #

更新時間:2019-11-21

2K+ 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.