Chức năng
start(int group) trả về offset bắt đầu 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 start = res.start(2); // bắt đầu group 2
System.out.println(start);
}
}
Kết quả
Nhập văn bản: This is a sample Text, 123
Match found
25
Giải thích
Group 2 = (\\d+) khớp "123" bắt đầu tại index 25 (sau "This is a sample Text, ").
Các phương thức liên quan
start()- bắt đầu toàn bộ match (group 0)end(int group)- kết thúc groupgroup(int group)- nội dung group