简单字符类“ [] ”匹配其中的所有指定字符。元字符^在上述字符类中用作否定符,即以下表达式匹配除b以外的所有字符(包括空格和特殊字符)
"[^b]"
同样,以下表达式匹配给定输入字符串中的所有辅音。
"([^aeiouyAEIOUY0-9\\W]+)";
然后,您可以使用replaceAll()方法,通过将匹配的字符替换为空字符串“”来删除匹配的字符。
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
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.compile(regex);
//匹配字符串中的编译模式
Matcher matcher = pattern.matcher(input);
//创建一个空字符串缓冲区
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n"+ sb.toString() );
}
}输出结果
输入字符串: # Hello how are you welcome to ooo # Result: # eo o ae you eoe o ooo #