Chức năng
end(int group) trả về offset sau ký tự cuối của group chỉ định 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 Example {
public static void main(String[] args) {
String regex = "(.*)(\\d+)(.*)";
Scanner sc = new Scanner(System.in);
System.out.println("Nhập văn bản: ");
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); // kết thúc group 1
System.out.println(end);
}
}
Kết quả
Nhập văn bản: This is a sample Text, 123
Match found
25
Giải thích
Group 1 = (.*) khớp "This is a sample Text, " (độ dài 25, index 0-24). end(1) trả về 25.