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

MatchResult start() Method ใน Java

Interface java.util.regex.MatchResult เมธอด start() คืนค่า beginning index ของการจับคู่ปัจจุบัน (กลุ่ม 0 = ทั้งหมด)

ตัวอย่าง

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

public class StartExample {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a String");
        String input = sc.nextLine();
        String regex = "\\W";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        
        if (matcher.find()) {
            System.out.println("Match occurred");
        } else {
            System.out.println("Match not occurred");
        }
        
        MatchResult res = matcher.toMatchResult();
        int start = res.start();
        System.out.println(start);
    }
}

ผลลัพธ์

Enter a String: This * is # sample % text with & non word characters
Match occurred
4

อธิบาย

  • Input: "This * is # sample % text with & non word characters"
  • Regex: \W = non-word character (ไม่ใช่ [a-zA-Z0-9_])
  • ตัวอักษรแรกที่ไม่ใช่ word character: * (asterisk) ที่ index 4
  • "This" = index 0,1,2,3 | space = index 4? ไป * อยู่ index 4
  • start() คืน 4

รายละเอียด Index

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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
Char:  T  h  i  s     *     i  s     #     s  a  m  p  l  e     %     t  e  x  t     w  i  t  h     &     n  o  n     w  o  r  d     c  h  a  r  a  c  t  e  r  s
       |_______________|  word chars (T,h,i,s)
       index 4 = * (non-word)

สรุป MatchResult Methods

Methodคืนค่าตัวอย่าง (\W แรก)
start()เริ่มต้นของ match4
end()หลังสิ้นสุดของ match5
group()ข้อความที่จับคู่"*"
groupCount()จำนวน capturing groups0
start(int group)เริ่มต้นของกลุ่มที่ระบุN/A
end(int group)สิ้นสุดของกลุ่มที่ระบุN/A
group(int group)ข้อความของกลุ่มที่ระบุN/A

MatchResult vs Matcher

  • Matcher - mutable, state เปลี่ยนตาม find()/reset()
  • MatchResult - immutable snapshot, ได้จาก matcher.toMatchResult()
  • ใช้ MatchResult เมื่อ: ต้องการส่งต่อผลลัพธ์, multi-threading, เก็บ history