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

Matcher region(int start, int end) Method ใน Java พร้อมตัวอย่าง


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

เมธอด region() ของคลาส (Matcher) นี้รับค่าจำนวนเต็มสองค่าที่แทนตำแหน่งในสตริงอินพุต และตั้ง region ของ matcher ปัจจุบัน

ตัวอย่างที่ 1: ตั้ง region(0,4) กับ regex \\A(?=\\w{6,10}\\z)

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

public class RegionExample {
    public static void main(String[] args) {
        // Regular expression ยอมรับ 6 ถึง 10 ตัวอักษร
        String regex = "\\A(?=\\w{6,10}\\z)";
        System.out.println("Enter 5 to 12 characters: ");
        String input = new Scanner(System.in).next();
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        // สร้าง Matcher object
        Matcher matcher = pattern.matcher(input);
        
        // ตั้ง region ให้กับสตริงอินพุต
        matcher.region(0, 4);
        
        // สลับไปใช้ transparent bounds
        if (matcher.find()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
    }
}

Output

Enter 5 to 12 characters: sampleText
Match not found

ตัวอย่างที่ 2: ตั้ง region(0,20) กับ regex (.*)(\\d+)(.*)

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

public class RegionExample {
    public static void main(String[] args) {
        String regex = "(.*)(\\d+)(.*)";
        String input = "This is a sample Text, 1234, with numbers in between.";
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        // สร้าง Matcher object
        Matcher matcher = pattern.matcher(input);
        
        // ตั้ง region ของ matcher
        matcher.region(0, 20);
        
        if (matcher.matches()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
    }
}

Output

Match not found