如何使用 Java 中的正则表达式从字符串中删除辅音?
javaobject oriented programmingprogramming更新于 2024/5/11 5:32:17
简单字符类"[ ]"匹配其中的所有指定字符。元字符 ^ 在上述字符类中充当否定,即以下表达式匹配除 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: 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("输入输入字符串: ");
String input = sc.nextLine();
String regex = "([^aeiouyAEIOUY0-9\W])";
String constants = "";
//创建一个 Pattern 对象
Pattern pattern = Pattern.compile(regex);
//匹配字符串中的编译模式
Matcher matcher = pattern.matcher(input);
//创建一个空的字符串缓冲区
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("结果: \n"+ sb.toString() );
}
}
输出
输入输入字符串: # Hello how are you welcome to Tutorialspoint # 结果: # eo o ae you eoe o uoiaoi #
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

