java.util.regex.Matcher class แสดงถึงเอ็นจิ้นที่ดำเนินการจับคู่ต่างๆ ไม่มีตัวสร้างสำหรับคลาสนี้ คุณสามารถสร้าง/รับวัตถุของคลาสนี้โดยใช้เมธอดmatch() ของคลาส java.util.regex.Pattern
hitEnd() วิธีการตรวจสอบว่าสิ้นสุดของข้อมูลที่ป้อนเข้ามาในระหว่างการแข่งขันก่อนหน้านี้ถ้าเป็นเช่นนั้นจะส่งกลับจริงอื่นเท็จ หากวิธีนี้คืนค่าเป็น จริง แสดงว่าข้อมูลที่ป้อนมากขึ้นอาจเปลี่ยนผลลัพธ์ของการจับคู่
ตัวอย่างเช่น หากคุณกำลังพยายามจับคู่คำสุดท้ายของสตริงอินพุตกับคุณโดยใช้ regex “you$” และหากบรรทัดอินพุตที่ 1 ของคุณคือ “hello how are you” คุณอาจมีการจับคู่ แต่ถ้าคุณยอมรับประโยคเพิ่มเติม คำสุดท้ายของบรรทัดใหม่อาจไม่ใช่คำที่กำหนด (ซึ่งก็คือ "คุณ") ทำให้ผลการจับคู่ของคุณเป็นเท็จ ในกรณีดังกล่าว เมธอด hitEnd() จะคืนค่าเป็นจริง
ตัวอย่าง
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HitEndExample {
public static void main( String args[] ) {
String regex = "you$";
//Reading input from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
//Instantiating the Pattern class
Pattern pattern = Pattern.compile(regex);
//Instantiating the Matcher class
Matcher matcher = pattern.matcher(input);
//verifying whether a match occurred
if(matcher.find()) {
System.out.println("Match found");
}
boolean result = matcher.hitEnd();
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");
}
}
} ผลลัพธ์
Enter input text: Hello how are you Match found More input may turn the result of the match false