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

MatchResult end(int group) Method ใน Java

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

ตัวอย่าง

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 = "(.*)(\\d+)(.*)";
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input text: ");
        String input = sc.nextLine();
        
        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(1);  // กลุ่มที่ 1
        System.out.println(end);
    }
}

ผลลัพธ์

Enter input text: This is a sample Text, 123
Match found
25

อธิบาย

  • Input: "This is a sample Text, 123"
  • Regex: (.*)(\\d+)(.*) - 3 กลุ่ม
  • Group 1: (.*) = "This is a sample Text, 12" (greedy ดูดเกือบหมด)
  • Group 2: (\\d+) = "3"
  • Group 3: (.*) = "" (ว่าง)
  • res.end(1) คืน 25 = index หลัง '2' ของ "12"

รายละเอียดตำแหน่ง

Index:  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Char:   T  h  i  s     i  s     a     s  a  m  p  l  e     T  e  x  t  ,     1  2  3
Group1: |_______________________________________________________________|
Group2:                                              |_________________|
Group3:                                                                     |_| (empty)

Group 1 จบที่ index 24 (ตัว '2') → end(1) = 25

เมธอด end() ทั้งหมด

  • end() = end(0) = ตำแหน่งหลังการจับคู่ทั้งหมด
  • end(int group) = ตำแหน่งหลังกลุ่มที่ระบุ
  • ความยาวกลุ่ม = end(group) - start(group)