如何使用 Java 中的正则表达式从字符串中删除元音?
javaobject oriented programmingprogramming更新于 2024/5/11 6:04:17
简单字符类"[ ]"匹配其中的所有指定字符。以下表达式匹配除 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: 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("输入输入字符串: ");
String input = sc.nextLine();
String regex = "[aeiouAEIOU]";
String constants = "";
System.out.println("输入字符串: \n"+input);
//创建一个 Pattern 对象
Pattern pattern = Pattern.compile(regex);
//匹配字符串中的编译模式
Matcher matcher = pattern.matcher(input);
//创建一个空的字符串缓冲区
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
constants = constants+matcher.group();
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("结果: \n"+ sb.toString()+constants );
}
}
输出
输入输入字符串: this is a sample text 输入字符串: this is a sample text Result: ths s smpl txtiiaaee
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

