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

MatchResult start(int group) Method ใน Java

Interface java.util.regex.MatchResult เมธอด start(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 start = res.start(2);  // กลุ่มที่ 2
        System.out.println(start);
    }
}

ผลลัพธ์

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

อธิบาย

  • Input: "This is a sample Text, 123"
  • Regex: (.*)(\\d+)(.*) - 3 capturing groups
  • Group 1: (.*) = "This is a sample Text, 12" (greedy)
  • Group 2: (\\d+) = "3" (ตัวเลขตัวสุดท้าย)
  • Group 3: (.*) = "" (ว่าง)
  • res.start(2) คืน 25 = index ของ '3' (ตัวแรกของกลุ่มที่ 2)

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

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:                                              |_________________|  (index 25)
Group3:                                                                     |_| (empty)

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

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

MatchResult vs Matcher

  • Matcher.start(int) - ใช้กับ matcher ปัจจุบัน (stateful)
  • MatchResult.start(int) - ใช้กับ snapshot (immutable) จาก toMatchResult()
  • MatchResult ปลอดภัยกว่าสำหรับ multi-threading หรือเก็บไว้ใช้ภายหลัง