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

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


Chức năng

end() trả về offset sau ký tự cuối của toàn bộ match (group 0).

Ví dụ

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);
    }
}

Kết quả

Nhập văn bản: hello how are you
Match found
17

Giải thích

Chuỗi "Hello how are you" độ dài 17 (index 0-16). Match "you" ở cuối, end() = 17.