java.util.regex.Matcher 클래스는 다양한 매칭(match) 연산을 수행하는 엔진 역할을 하는 클래스입니다. 이 클래스는 별도의 생성자가 제공되지 않으며, java.util.regex.Pattern 클래스의 matcher() 메서드를 호출하여 객체를 생성하거나 얻을 수 있습니다.
Matcher 클래스의 regionEnd() 메서드는 현재 매처(Matcher) 객체에 설정된 검색 영역(region)의 끝 인덱스를 나타내는 정수 값을 반환합니다. 검색 영역은 region(int start, int end) 메서드를 통해 설정할 수 있으며, 이를 통해 입력 문자열 전체가 아닌 특정 구간만 대상으로 매칭 작업을 수행할 수 있습니다.
regionEnd() 메서드의 주요 특징
- 반환 타입: int (현재 영역의 끝 인덱스)
- 매개변수: 없음
- region() 메서드로 설정된 영역의 end 값과 동일한 값을 반환
예제 1: 기본적인 regionEnd() 사용법
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionEndExample {
public static void main(String[] args) {
String regex = "(.*)(\\d+)(.*)";
String input = "This is a sample Text, 1234, with numbers in between.";
// 패턴 객체 생성
Pattern pattern = Pattern.compile(regex);
// Matcher 객체 생성
Matcher matcher = pattern.matcher(input);
// 매처의 검색 영역 설정
matcher.region(5, 20);
if(matcher.matches()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
System.out.print("End of the region: "+matcher.regionEnd());
}
}실행 결과
Match not found End of the region: 20
위 예제에서는 region(5, 20) 메서드를 호출하여 인덱스 5부터 20까지의 구간만 검색 대상으로 지정했습니다. matches() 메서드는 해당 영역 전체가 정규식과 일치해야 하므로, 숫자(1234)가 포함된 부분이 영역 밖에 있어 매칭에 실패했습니다. 그리고 regionEnd() 메서드는 설정된 영역의 끝 인덱스인 20을 반환합니다.
예제 2: 사용자 입력 문자열에 적용하기
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionEndExample {
public static void main(String[] args) {
// '#' 문자를 찾는 정규 표현식
String regex = "[#]";
System.out.println("Enter a string: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// 패턴 객체 생성
Pattern pattern = Pattern.compile(regex);
// Matcher 객체 생성
Matcher matcher = pattern.matcher(input);
// 입력 문자열에 검색 영역 설정
matcher.region(2, 4);
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
System.out.println("Ending of the region: "+ matcher.regionEnd());
}
}실행 결과
Enter a string: this is sample text # Match not found Ending of the region: 4
이 예제에서는 사용자로부터 문자열을 입력받은 후, region(2, 4)으로 인덱스 2부터 4까지의 구간만 검색하도록 설정했습니다. '#' 문자는 해당 구간에 존재하지 않으므로 find() 메서드가 false를 반환하며, regionEnd() 메서드는 4를 출력합니다.
정리
regionEnd() 메서드는 Matcher 객체의 현재 검색 영역이 어디서 끝나는지 확인할 때 유용하게 사용됩니다. regionStart() 메서드와 함께 활용하면 현재 설정된 검색 범위를 손쉽게 파악할 수 있어, 복잡한 문자열 처리 로직을 디버깅하거나 설계할 때 큰 도움이 됩니다.