如何在 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 #
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP