Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Phương thức MatchResult start() trong Java


Chức năng

start() trả về index bắt đầu của toàn bộ match (group 0) trong match cuối.

Ví dụ

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("Nhập chuỗi: ");
        String input = sc.nextLine();
        String regex = "\\W"; // non-word char
        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);
    }
}

Kết quả

Nhập chuỗi: This * is # sample % text with & non word characters
Match occurred
4

Giải thích

Chuỗi: "This * is # sample % text with & non word characters"

  • Index 0:T, 1:h, 2:i, 3:s, 4:space (non-word? Không, space là \s)
  • Thực tế: \\W = non-word = không phải [a-zA-Z0-9_]. Space KHÔNG phải word char → khớp tại index 4 (khoảng trắng sau "This").

Lưu ý

  • start() chỉ hợp lệ sau khi find(), matches(), hoặc lookingAt() thành công.
  • Gọi trước khi match → ném IllegalStateException.