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

MatchResult end() Method ใน Java

Interface java.util.regex.MatchResult เมธอด end() คืนค่า offset (index) หลัง ตัวอักษรสุดท้ายของการจับคู่ (กลุ่ม 0 = ทั้งหมด)

ตัวอย่าง

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

public class Example {
    public static void main(String args[]) {
        String regex = "you$";
        Scanner sc = new Scanner(System.in);
        String input = "Hello how are you";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        
        if (matcher.find()) {
            System.out.println("Match found");
        }
        
        MatchResult res = matcher.toMatchResult();
        int end = res.end();
        System.out.println(end);
    }
}

ผลลัพธ์

Enter input text: hello how are you
Match found
17

อธิบาย

  • Input: "Hello how are you" (ความยาว 17 ตัวอักษร index 0-16)
  • Regex: you$ จับคู่ "you" ที่ท้ายสตริง
  • "you" อยู่ index 14,15,16
  • end() คืน 17 = index หลังตัวสุดท้าย = ความยาวสตริง

การใช้งานร่วมกับ start()

  • start() = 14 (index ของ 'y')
  • end() = 17
  • ความยาว = 17 - 14 = 3 ("you")
  • substring = input.substring(start(), end()) = "you"

สรุป MatchResult Methods

Methodคืนค่าตัวอย่าง (you ที่ index 14-16)
start()เริ่มต้นของ match14
end()หลังสิ้นสุดของ match17
group()ข้อความที่จับคู่"you"
groupCount()จำนวน capturing groups0 (ไม่มีวงเล็บ)

MatchResult vs Matcher

  • Matcher - mutable, สถานะเปลี่ยนไปตาม find()/reset()
  • MatchResult - immutable snapshot, ปลอดภัยสำหรับส่งต่อ/เก็บไว้
  • ได้จาก matcher.toMatchResult() (Java 5+)