Matcher 클래스란?
java.util.regex.Matcher 클래스는 다양한 매칭(match) 연산을 수행하는 엔진 역할을 하는 클래스입니다. 이 클래스는 별도의 생성자가 제공되지 않으며, java.util.regex.Pattern 클래스의 matcher() 메서드를 호출하여 객체를 생성하거나 얻을 수 있습니다.
requireEnd() 메서드의 동작 원리
매칭이 성공했을 때, Matcher 클래스의 requireEnd() 메서드는 추가 입력이 들어올 경우 기존 매칭 결과가 false로 바뀔 가능성이 있는지를 검사합니다. 만약 더 많은 입력으로 인해 매칭 결과가 거짓이 될 가능성이 있다면 true를 반환하고, 그렇지 않다면 false를 반환합니다.
requireEnd()가 true를 반환하는 경우
예를 들어, 입력 문자열의 마지막 단어가 "you"인지 확인하기 위해 정규식 "you$"를 사용한다고 가정해 보겠습니다. 첫 번째 입력 줄이 "hello how are you"라면 매칭에 성공할 수 있습니다. 하지만 이후 추가 문장을 입력받게 되면 새로운 줄의 마지막 단어가 "you"가 아닐 수 있으며, 이 경우 매칭 결과는 false가 됩니다. 이처럼 추가 입력이 결과를 바꿀 수 있는 상황에서는 requireEnd() 메서드가 true를 반환합니다.
requireEnd()가 false를 반환하는 경우
반대로, 입력에서 특정 문자(예: #)를 찾는 경우를 생각해 보겠습니다. 첫 번째 입력 줄이 "Hello # how are you"라면 매칭에 성공합니다. 이후 더 많은 입력 데이터가 들어와도 매처(matcher)의 내용은 변경될 수 있지만, 이미 발견된 매칭 결과 자체는 변하지 않습니다. 이런 시나리오에서는 requireEnd() 메서드가 false를 반환합니다.
예제 1: 문장 끝 단어 매칭
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RequiredEndExample {
public static void main( String args[] ) {
String regex = "you$";
// 사용자로부터 입력 받기
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");
}
boolean result = matcher.requireEnd();
if(result) {
System.out.println("More input may turn the result of the match false");
} else{
System.out.println("The result of the match will be true, inspite of more data");
}
}
}실행 결과
Enter input text: Hello how are you Match found More input may turn the result of the match false
위 예제에서 정규식 "you$"는 문자열의 끝에 위치한 "you"만 매칭하기 때문에, 추가 입력이 들어오면 마지막 단어가 달라질 수 있습니다. 따라서 requireEnd()는 true를 반환하여 "추가 입력이 매칭 결과를 false로 바꿀 수 있다"고 알려줍니다.
예제 2: 특수 문자 매칭
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RequiredEndExample {
public static void main( String args[] ) {
String regex = "[#]";
// 사용자로부터 입력 받기
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");
}
boolean result = matcher.requireEnd();
if(result) {
System.out.println("More input may turn the result of the match false");
} else{
System.out.println("The result of the match will be true, inspite of more data");
}
}
}실행 결과
Enter input text: Hello# how# are you Match found The result of the match will be true, in spite of more data
이 예제에서 정규식 "[#]"는 입력 어디에든 존재하는 # 문자를 찾습니다. 한 번 매칭에 성공하면 이후 입력이 추가되더라도 이미 발견된 # 문자가 사라지는 것은 아니므로, 매칭 결과는 안정적으로 유지됩니다. 따라서 requireEnd()는 false를 반환합니다.
정리
requireEnd() 메서드는 특히 스트림 형태로 입력을 점진적으로 읽어들이는 상황에서 유용합니다. 현재까지의 입력으로 매칭에 성공했더라도, 이후 입력에 따라 결과가 뒤집힐 수 있는지 사전에 판단함으로써 더 안전하고 신뢰성 있는 정규식 처리 로직을 작성할 수 있습니다.