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

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


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

Anchoring bounds ใช้จับคู่ region matches เช่น ^ และ $ โดยค่าเริ่มต้น matcher ใช้ anchoring bounds

เมธอด useAnchoringBounds() ของคลาสนี้รับค่า boolean และ หากคุณส่ง true ให้เมธอดนี้ matcher ปัจจุบันจะใช้ anchoring bounds และหากส่ง false จะใช้ non-anchoring bounds

ตัวอย่างที่ 1: ตรวจสอบ anchoring bounds

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

public class Trail {
    public static void main(String args[]) {
        // อ่านค่าสตริง
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input string");
        String input = sc.nextLine();
        
        // Regular expression เพื่อหาตัวเลข
        String regex = ".*\\d+.*";
        
        // คอมไพล์ regular expression
        Pattern pattern = Pattern.compile(regex);
        
        // พิมพ์ regular expression
        System.out.println("Compiled regular expression: " + pattern.toString());
        
        // ดึง Matcher object
        Matcher matcher = pattern.matcher(input);
        matcher.useAnchoringBounds(false);
        boolean hasBounds = matcher.hasAnchoringBounds();
        
        if (hasBounds) {
            System.out.println("Current matcher uses anchoring bounds");
        } else {
            System.out.println("Current matcher uses non-anchoring bounds");
        }
    }
}

Output

Enter input string sample
Compiled regular expression: .*\d+.*
Current matcher uses non-anchoring bounds

ตัวอย่างที่ 2: ใช้ non-anchoring bounds

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

public class Sample {
    public static void main(String args[]) {
        String regex = "^<foo>.*";
        String input = "<foo><bar>";//Hi</i></br> welcome to Tutorialspoint";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        matcher = matcher.useAnchoringBounds(false);
        
        if (matcher.matches()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
        System.out.println("Has anchoring bounds: " + matcher.hasAnchoringBounds());
    }
}

Output

Match found
Has anchoring bounds: false