Character Class ใน Java Regex ใช้วงเล็บสี่เหลี่ยม [] จับคู่ตัวอักษรตัวเดียวจากชุดที่ระบุ เช่น [abc] จับคู่ a, b, c
รูปแบบ Range ใช้ไฮเฟน - ระบุช่วงตัวอักษร เช่น [a-z] จับคู่พิมพ์เล็ก a ถึง z และ [^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 characters from the range (a-z): " + count);
}
}
ผลลัพธ์
Enter input text: sample data 5423 #@ %*&
Number characters from the range (a-z): 10
ตัวอย่าง 2: Negation Range [^A-Z]
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample3 {
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;
if (matcher.find()) {
System.out.println("match occurred");
} else {
System.out.println("match not occurred");
}
}
}
ผลลัพธ์
Enter input text: sample data
match occurred
Enter input text: SAMPLEDATA
match not occurred
สรุป
[a-z]- ช่วงพิมพ์เล็ก[A-Z]- ช่วงพิมพ์ใหญ่[0-9]- ช่วงตัวเลข[^A-Z]- ไม่ใช่พิมพ์ใหญ่ (Negation)- สามารถรวมช่วงได้ เช่น
[a-zA-Z0-9]