Khái niệm
Intersection (giao) khớp ký tự chung của hai phạm vi. Cú pháp: [range1&&range2] hoặc [range1&&[range2]].
Ví dụ: [a-z&&[r-u]]
Giao của a-z và r-u → r,s,t,u
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Nhập văn bản: ");
String input = sc.nextLine();
String regex = "[a-z&&[r-u]]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Số ký tự khớp: " + count);
}
}
Kết quả
Nhập văn bản: how are you welcome to tutorialspoint
Số ký tự khớp: 9
Giải thích
Chuỗi có các ký tự r-u: r (3 lần), s (1), t (3), u (2) = 9.
Ứng dụng
- Lọc ký tự thuộc nhiều tiêu chí:
[\p{Alpha}&&[^AEIOUaeiou]]= phụ âm - Kết hợp Unicode block:
[\p{InGreek}&&[^\\p{Lu}]]= Greek chữ thường