Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Matcher hitEnd() Method ใน Java พร้อมตัวอย่าง


คลาส java.util.regex.Matcher แทน engine ที่ดำเนินการจับคู่ต่างๆ ไม่มี constructor สำหรับคลาสนี้ คุณสามารถสร้าง/ได้รับ object ของคลาสนี้โดยใช้เมธอด matches() ของคลาส java.util.regex.Pattern

เมธอด hitEnd() ตรวจสอบว่าสิ้นสุดของข้อมูลอินพุตถูกถึงระหว่างการจับคู่ครั้งก่อนหรือไม่ หากใช่ จะคืนค่า true มิฉะนั้น false หากเมธอดนี้คืนค่า true แสดงว่าข้อมูลอินพุตเพิ่มเติมอาจเปลี่ยนผลลัพธ์ของการจับคู่

เช่น หากคุณพยายามจับคู่คำสุดท้ายของสตริงอินพุตเป็น "you" โดยใช้ regex "you$" และบรรทัดแรกของคุณคือ "hello how are you" คุณอาจมี match แต่ หากคุณยอมรับประโยคเพิ่มเติม คำสุดท้ายของบรรทัดใหม่อาจไม่ใช่คำที่ต้องการ (ซึ่งคือ "you") ทำให้ผลการจับคู่เป็น false ในกรณีเช่นนี้ hitEnd() จะคืนค่า true

ตัวอย่าง

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$";
        
        // อ่านอินพุตจากผู้ใช้
        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.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");
        }
    }
}

Output

Enter input text: Hello how are you
Match found
More input may turn the result of the match false