Character Class ใน Java Regex ใช้ [] จับคู่ตัวอักษรตัวเดียวจากชุดที่ระบุ เช่น [abc] จับคู่ a, b, c หรือ [a-z] จับคู่พิมพ์เล็ก a-z
ตัวอย่าง 1: นับตัวอักษร a-z
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]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Number of characters from a to z: " + count);
}
}
ผลลัพธ์
Enter input text: sample data 1234$
Number of characters from a to z: 10
ตัวอย่าง 2: นับตัวอักษรที่ไม่ใช่ a-z (Negation)
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]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Number of non-alphabetic characters: " + count);
}
}
ผลลัพธ์
Enter input text: sample data 1234$
Number of non-alphabetic characters: 7
สรุป Character Class พื้นฐาน
| Pattern | ความหมาย | ตัวอย่างจับคู่ |
|---|---|---|
[abc] | a หรือ b หรือ c | a, b, c |
[a-z] | พิมพ์เล็ก a ถึง z | a, m, z |
[A-Z] | พิมพ์ใหญ่ A ถึง Z | A, M, Z |
[0-9] | ตัวเลข 0 ถึง 9 | 0, 5, 9 |
[^a-z] | ไม่ใช่พิมพ์เล็ก | A, 1, @, space |
[a-zA-Z0-9] | ตัวอักษรและตัวเลข | a, Z, 5 |