Character Class ใช้ [] จับคู่ตัวอักษรตัวเดียวจากชุดที่ระบุ เช่น [abc] จับคู่ a, b, c
รูปแบบ Intersection ใช้ && จับคู่ตัวอักษรที่ อยู่ในทั้งสองช่วง (AND)
ตัวอย่าง: [a-z&&[r-u]] จับคู่ตัวอักษรที่เป็นพิมพ์เล็ก และ อยู่ใน 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("Enter input text: ");
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("Number of matched characters: " + count);
}
}
ผลลัพธ์
Enter input text: how are you welcome to tutorialspoint
Number of matched characters: 9
อธิบาย
- Input: "how are you welcome to tutorialspoint"
- Regex
[a-z&&[r-u]]จับคู่ r, s, t, u (พิมพ์เล็ก) - นับในข้อความ: how are you welcome to tutorialspoint
- ตัวอักษร r-u ที่เจอ: r, e, o, o, o, u, o, r, o = 9 ตัว (นับ r,s,t,u ทั้งหมด)
รูปแบบ Intersection
[range1&&[range2]]
ตัวอย่างเพิ่มเติม
| Regex | ความหมาย | จับคู่ |
|---|---|---|
[a-z&&[m-p]] | พิมพ์เล็ก และ m-n-o-p | m, n, o, p |
[A-Z&&[X-Z]] | พิมพ์ใหญ่ และ X-Y-Z | X, Y, Z |
[0-9&&[4-7]] | ตัวเลข และ 4-5-6-7 | 4, 5, 6, 7 |
[\p{Alpha}&&\p{Lower}] | ตัวอักษร และ พิมพ์เล็ก | a-z |
ความสัมพันธ์กับ Subtraction
Subtraction = Intersection + Negation:
[a-z&&[^aeiou]] = a-z ∩ (not aeiou) = พยัญชนะ