แพ็กเกจ java.util.regex ของ Java มีคลาสต่างๆ สำหรับค้นหารูปแบบเฉพาะในลำดับตัวอักษร คลาส Pattern ของแพ็กเกจนี้เป็นการแสดงรูปแบบที่คอมไพล์แล้วของนิพจน์ปกติ เมธอด matcher() ของคลาสนี้รับออบเจ็กต์ของคลาส CharSequence ที่แทนสตริงอินพุต และส่งคืนออบเจ็กต์ Matcher ซึ่งจะจับคู่สตริงที่กำหนดกับนิพจน์ปกติที่แสดงโดยออบเจ็กต์ Pattern ปัจจุบัน
ตัวอย่าง
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample {
public static void main(String args[]) {
// อ่านค่าสตริง
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string");
String input = sc.nextLine();
// นิพจน์ปกติเพื่อค้นหาสระ
String regex = "[aeiou]";
// คอมไพล์นิพจน์ปกติ
Pattern pattern = Pattern.compile(regex);
// ดึงออบเจ็กต์ matcher
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Given string contains vowels");
} else {
System.out.println("Given string does not contain vowels");
}
}
}ผลลัพธ์
Enter input string RHYTHM Given string does not contain vowels