如何在 Java 中使用正则表达式从字符串中移除元音?
简单的字符类“[ ]”匹配其中所有指定的字符。以下表达式匹配除了 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);
}
}输出
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("Enter input string: ");
String input = sc.nextLine();
String regex = "[aeiouAEIOU]";
String constants = "";
System.out.println("Input string: \n"+input);
//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()) {
constants = constants+matcher.group();
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n"+ sb.toString()+constants );
}
}输出
Enter input string: this is a sample text Input string: this is a sample text Result: ths s smpl txtiiaaee
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP