คลาส java.util.regex.Matcher แทน engine ที่ดำเนินการจับคู่ต่างๆ ไม่มี constructor สำหรับคลาสนี้ คุณสามารถสร้าง/ได้รับ object ของคลาสนี้โดยใช้เมธอด matches() ของคลาส java.util.regex.Pattern
ในกรณีของการจับคู่ เมธอด requireEnd() ของคลาส (Matcher) นี้ตรวจสอบว่ามีโอกาสที่ผลการจับคู่จะเป็น false หากมีอินพุตเพิ่มเติม หากใช่ เมธอดนี้คืนค่า true มิฉะนั้น false
เช่น หากคุณพยายามจับคู่คำสุดท้ายของสตริงอินพุตเป็น "you" โดยใช้ regex "you$" และบรรทัดแรกของคุณคือ "hello how are you" คุณอาจมี match แต่ หากคุณยอมรับประโยคเพิ่มเติม คำสุดท้ายของบรรทัดใหม่อาจไม่ใช่คำที่ต้องการ (ซึ่งคือ "you") ทำให้ผลการจับคู่เป็น false ในกรณีเช่นนี้ requiredEnd() จะคืนค่า true
เช่นเดียวกัน หากคุณพยายามจับคู่ตัวอักษรเฉพาะในอินพุตคือ # และบรรทัดแรกของคุณคือ "Hello # how are you" คุณจะมี match และ ข้อมูลอินพุตเพิ่มเติมอาจเปลี่ยนเนื้อหาของ matcher แต่ไม่เปลี่ยนผลลัพธ์ซึ่งเป็น true ในสถานการณ์นี้ requiredEnd() จะคืนค่า false
ตัวอย่างที่ 1: regex you$ ต้องการ end of string
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RequiredEndExample {
public static void main(String args[]) {
String regex = "you$";
// อ่านอินพุตจากผู้ใช้
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
// สร้าง Pattern class
Pattern pattern = Pattern.compile(regex);
// สร้าง Matcher class
Matcher matcher = pattern.matcher(input);
// ตรวจสอบว่ามีการจับคู่เกิดขึ้นหรือไม่
if (matcher.find()) {
System.out.println("Match found");
}
boolean result = matcher.requireEnd();
if (result) {
System.out.println("More input may turn the result of the match false");
} else {
System.out.println("The result of the match will be true, inspite of more data");
}
}
}
Output
Enter input text: Hello how are you Match found More input may turn the result of the match false
ตัวอย่างที่ 2: regex [#] ไม่ต้องการ end of string
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RequiredEndExample {
public static void main(String args[]) {
String regex = "[#]";
// อ่านอินพุตจากผู้ใช้
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
// สร้าง Pattern class
Pattern pattern = Pattern.compile(regex);
// สร้าง Matcher class
Matcher matcher = pattern.matcher(input);
// ตรวจสอบว่ามีการจับคู่เกิดขึ้นหรือไม่
if (matcher.find()) {
System.out.println("Match found");
}
boolean result = matcher.requireEnd();
if (result) {
System.out.println("More input may turn the result of the match false");
} else {
System.out.println("The result of the match will be true, in spite of more data");
}
}
}
Output
Enter input text: Hello# how# are you Match found The result of the match will be true, in spite of more data