เมธอด start() ของคลาส java.util.regex.Matcher จะคืนค่าตำแหน่งเริ่มต้นของการแข่งขัน (หากมีการจับคู่เกิดขึ้น)
ในทำนองเดียวกัน เมธอด end() ของคลาส Matcher จะคืนค่าตำแหน่งสิ้นสุดของการแข่งขัน
ดังนั้น ค่าตอบแทนของเมธอด start() จะเป็นตำแหน่งเริ่มต้นของการจับคู่ และความแตกต่างระหว่างค่าที่ส่งคืนของเมธอด end() และ start() จะเป็นความยาวของการแข่งขัน
ตัวอย่าง
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample {
public static void main(String[] args) {
int start = 0, len = -1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "\\d+";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
start = matcher.start();
len = matcher.end()-start;
}
System.out.println("Position of the match : "+start);
System.out.println("Length of the match : "+len);
}
} ผลลัพธ์
Enter input text: sample data with digits 12345 Position of the match : 24 Length of the match : 5