Chức năng
\E kết thúc quoting bắt đầu bằng \Q. Các metacharacter giữa \Q...\E bị escape, thành literal.
Ví dụ 1: Không \Q\E
String regex = "[aeiou]";
// Khớp bất kỳ nguyên âm
"sample" -> Match occurred
Ví dụ 2: Có \Q\E
String regex = "\\Q[aeiou]\\E";
// Khớp chuỗi literal "[aeiou]"
"sample" -> Match not occurred
"The letters [aeiou] are vowels" -> Match occurred
Code đầy đủ
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleProgram {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Nhập chuỗi: ");
String input = sc.nextLine();
String regex = "\\Q[aeiou]\\E";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
}
Ứng dụng thực tế
// An toàn hơn: dùng Pattern.quote()
String userInput = "[test]";
String regex = Pattern.quote(userInput); // tự động \Q[test]\E
Pattern p = Pattern.compile(regex);
Lưu ý
- \Q...\E không lồng được (nested).
- Trong replacement string của replaceAll, dùng
Matcher.quoteReplacement().