Java에서 정규식으로 문자열을 검색할 때, 매칭된 결과가 어디서 시작하고 얼마나 긴지 알아야 하는 경우가 자주 있습니다. 이때 java.util.regex.Matcher 클래스가 제공하는 메서드를 활용하면 간단하게 해결할 수 있습니다.
start()와 end() 메서드
Matcher 클래스의 start() 메서드는 매칭이 성공했을 때 해당 결과가 시작되는 위치(인덱스)를 반환합니다.
마찬가지로 end() 메서드는 매칭이 끝나는 위치를 반환합니다.
따라서 다음과 같이 정리할 수 있습니다.
- 매칭 시작 위치:
start()메서드의 반환값 - 매칭 길이:
end()반환값에서start()반환값을 뺀 값
예제 코드
입력받은 문자열에서 숫자(\d+)를 찾아 그 위치와 길이를 출력하는 예제입니다.
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+";
// 패턴 객체 생성
Pattern pattern = Pattern.compile(regex);
// 컴파일된 패턴을 문자열에 적용
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
코드 설명
위 예제에서 입력 문자열 sample data with digits 12345에는 숫자 12345가 포함되어 있습니다. 이 숫자는 인덱스 24번째 위치에서 시작하며, 총 5자리이므로 길이는 5가 출력됩니다.
while (matcher.find()) 반복문을 사용하면 문자열 내에 매칭 결과가 여러 개 있더라도 모두 탐색할 수 있으며, 반복문이 끝난 후에는 마지막으로 매칭된 결과의 위치와 길이가 변수에 저장됩니다. 만약 매칭 결과가 하나도 없다면 초기값인 -1이 그대로 유지되므로, 이를 통해 매칭 실패 여부도 판단할 수 있습니다.