如何使用Java中的正则表达式从字符串中删除元音?
简单字符类“[]”匹配其中的所有指定字符。以下表达式匹配xyz以外的字符。
"[xyz]"
同样,以下表达式匹配给定输入字符串中的所有元音。
"([^aeiouAEIOU0-9\\W]+)";
然后,您可以使用空字符串“”替换匹配的字符,方法是使用replaceAll()方法。
例子1
public class RemovingVowels {
public static void main( String args[] ) {
String input = "Hi welcome to nhooo";
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("输入输入字符串: ");
String input = sc.nextLine();
String regex = "[aeiouAEIOU]";
String constants = "";
System.out.println("Input string: \n"+input);
//创建一个模式对象
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("Result: \n"+ sb.toString()+constants );
}
}输出结果输入输入字符串: this is a sample text Input string: this is a sample text Result: ths s smpl txtiiaaee