Lớp ký tự đơn giản “[]” khớp với tất cả các ký tự được chỉ định trong đó. Biểu thức sau khớp với các ký tự ngoại trừ xyz.
"[xyz]"
Tương tự, biểu thức sau khớp với tất cả các nguyên âm trong chuỗi đầu vào đã cho.
"([^aeiouAEIOU0-9\\W]+)";
Sau đó, bạn có thể xóa các ký tự phù hợp bằng cách thay thế chúng bằng chuỗi trống “”, sử dụng phương thức ReplaceAll ().
Ví dụ 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);
}
} Đầu ra
Result: H wlcm t ttrlspnt
Ví dụ 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 );
}
} Đầu ra
Enter input string: this is a sample text Input string: this is a sample text Result: ths s smpl txtiiaaee