java.util.regex.MatchResult 인터페이스는 정규식 매칭 결과를 조회할 수 있는 다양한 메서드를 제공합니다.
이 인터페이스의 객체는 Matcher 클래스의 toMatchResult() 메서드를 통해 얻을 수 있습니다. 이 메서드는 현재 매처(matcher)의 매칭 상태를 나타내는 MatchResult 객체를 반환하며, 이후에도 결과를 자유롭게 참조할 수 있습니다.
이 인터페이스의 start(int group) 메서드는 특정 그룹을 나타내는 정수를 인자로 받아, 해당 그룹이 캡처한 하위 시퀀스가 시작되는 위치(인덱스)를 반환합니다. 만약 지정한 그룹이 매칭에 실패했다면 IllegalStateException 또는 IndexOutOfBoundsException이 발생할 수 있으므로 주의해야 합니다.
예제
다음 예제는 사용자로부터 입력을 받아 정규식과 매칭한 후, 두 번째 그룹(숫자 부분)이 시작되는 인덱스를 출력합니다.
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("Enter input text: ");
String input = sc.nextLine();
// Pattern 클래스 객체 생성
Pattern pattern = Pattern.compile(regex);
// Matcher 클래스 객체 생성
Matcher matcher = pattern.matcher(input);
// 매칭 여부 확인
if(matcher.find()) {
System.out.println("Match found");
}
MatchResult res = matcher.toMatchResult();
int start = res.start(2);
System.out.println(start);
}
}실행 결과
Enter input text: This is a sample Text, 123 Match found 25
위 실행 결과에서 입력 문자열 "This is a sample Text, 123"에서 숫자 "123"은 인덱스 25부터 시작하므로, 두 번째 그룹의 시작 위치인 25가 출력됩니다.