java.util.regex.MatchResult 인터페이스는 정규식 매칭 결과를 조회할 수 있는 다양한 메서드를 제공합니다.
이 인터페이스의 객체는 Matcher 클래스의 toMatchResult() 메서드를 통해 얻을 수 있습니다. 이 메서드는 현재 매처(matcher)의 매칭 상태를 나타내는 MatchResult 객체를 반환합니다.
MatchResult 인터페이스의 start() 메서드는 현재 매칭이 시작되는 인덱스, 즉 시작 위치를 반환합니다.
start() 메서드 예제
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StartExample {
public static void main(String args[]) {
// 사용자로부터 문자열 입력받기
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\\W";
// 정규식 컴파일
Pattern pattern = Pattern.compile(regex);
// Matcher 객체 생성
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match occurred");
}else {
System.out.println("Match not occurred");
}
// MatchResult 객체 가져오기
MatchResult res = matcher.toMatchResult();
int start = res.start();
System.out.println(start);
}
}실행 결과
Enter a String This * is # sample % text with & non word characters Match occurred 4
코드 설명
위 예제에서 사용된 정규식 "\W"는 단어 문자가 아닌 문자(non-word character)를 의미합니다. 프로그램은 사용자가 입력한 문자열에서 이 패턴과 일치하는 첫 번째 위치를 찾습니다.
매칭이 발견되면 toMatchResult() 메서드를 호출하여 MatchResult 객체를 얻고, 이어서 start() 메서드를 호출해 매칭이 시작된 인덱스를 출력합니다.
실행 결과를 보면, 입력 문자열 "This * is # sample % text..."에서 '*' 문자가 4번째 인덱스에서 발견되었기 때문에 start() 메서드는 4를 반환합니다. Java에서 인덱스는 0부터 시작한다는 점에 유의하세요.