java.util.regex.Matcher 클래스의 start() 메소드는 일치의 시작 위치를 반환합니다(일치하는 경우).
마찬가지로 Matcher 클래스의 end() 메서드는 일치의 끝 위치를 반환합니다.
따라서 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