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

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


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

เมธอด lookingAt() ของคลาส Matcher จับคู่ข้อความอินพุตที่กำหนดกับ pattern เริ่มจากจุดเริ่มต้นของ region หากจับคู่ได้ เมธอดนี้คืนค่า true มิฉะนั้น false ต่างจากเมธอด matches() ที่ต้องการการจับคู่ทั่วทั้ง region

ตัวอย่างที่ 1: lookingAt() กับข้อความหลายบรรทัด

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        String regex = "(.*)(\\d+)(.*)";
        String input = "This is a sample Text, 1234, with numbers in between. " + "\n This is the second line in the text " + "\n This is third line in the text";
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        // สร้าง Matcher object
        Matcher matcher = pattern.matcher(input);
        
        // ตรวจสอบการจับคู่
        if (matcher.lookingAt()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
    }
}

Output

Match found

ตัวอย่างที่ 2: ใช้ Scanner รับ 3 สตริง

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LookingAtExample {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter String1: ");
        String input1 = sc.nextLine();
        System.out.println("Enter String2: ");
        String input2 = sc.nextLine();
        System.out.println("Enter String3: ");
        String input3 = sc.nextLine();
        String input = input1 + "\n" + input2 + "\n" + input3;
        System.out.println(input);
        
        // Regular expression จับคู่คำที่มีตัวเลข
        String regex = ".*\\d+.*";
        
        // คอมไพล์ regular expression
        Pattern pattern = Pattern.compile(regex);
        
        // ดึง Matcher object
        Matcher matcher = pattern.matcher(input);
        
        // ตรวจสอบว่ามีการจับคู่เกิดขึ้นหรือไม่
        boolean bool = matcher.lookingAt();
        if (bool) {
            System.out.println("Given input contains digit");
        } else {
            System.out.println("Given input does not contain any digit");
        }
    }
}

Output

Enter String1: sample text2
Enter String2: data
Enter String3: sample
sample text2
data
sample
Given input contains digit