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

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


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

เมธอด regionStart() ของคลาส (Matcher) นี้คืนค่าจำนวนเต็มที่แทน start index ของ matcher object ปัจจุบัน

ตัวอย่างที่ 1: ตั้ง region(2,4) แล้วหา #

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

public class RegionStartExample {
    public static void main(String[] args) {
        // Regular expression ยอมรับ 6 ถึง 10 ตัวอักษร
        String regex = "[#]";
        System.out.println("Enter a string: ");
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        // สร้าง Matcher object
        Matcher matcher = pattern.matcher(input);
        
        // ตั้ง region ให้กับสตริงอินพุต
        matcher.region(2, 4);
        
        // สลับไปใช้ transparent bounds
        if (matcher.find()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
        
        System.out.println("Starting of the region: " + matcher.regionStart());
    }
}

Output

Enter a string: #sample text
Match not found
Starting of the region: 2

ตัวอย่างที่ 2: ตั้ง region(5,20) แล้ว matches()

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

public class RegionStartExample {
    public static void main(String[] args) {
        String regex = "(.*)(\\d+)(.*)";
        String input = "124 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(5, 20);
        
        if (matcher.matches()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
        
        System.out.print("Start of the region: " + matcher.regionStart());
    }
}

Output

Match not found
Start of the region: 5