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

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


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

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

ตัวอย่างที่ 1: ตั้ง region(5,20)

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

public class RegionEndExample {
    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(5, 20);
        
        if (matcher.matches()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
        
        System.out.print("End of the region: " + matcher.regionEnd());
    }
}

Output

Match not found
End of the region: 20

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

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

public class RegionEndExample {
    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("Ending of the region: " + matcher.regionEnd());
    }
}

Output

Enter a string: this is sample text #
Match not found
Ending of the region: 4