java.util.regex แพ็คเกจของ java มีคลาสที่หลากหลายเพื่อค้นหารูปแบบเฉพาะในลำดับอักขระ
คลาสรูปแบบของแพ็คเกจนี้เป็นการแสดงนิพจน์ทั่วไปที่คอมไพล์แล้ว ตัวจับคู่() เมธอดของคลาสนี้ยอมรับออบเจกต์ของ CharSequence คลาสที่แสดงสตริงอินพุตและส่งคืนออบเจ็กต์ Matcher ซึ่งตรงกับสตริงที่กำหนดกับนิพจน์ทั่วไปที่แสดงโดยอ็อบเจ็กต์ (รูปแบบ) ปัจจุบัน
ตัวอย่าง
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample {
public static void main(String args[]) {
//Reading string value
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string");
String input = sc.nextLine();
//Regular expression to find vowels
String regex = "[aeiou]";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
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