Java Matcher 클래스란?
java.util.regex.Matcher 클래스는 정규 표현식을 기반으로 다양한 매칭(match) 작업을 수행하는 엔진을 나타냅니다. 이 클래스에는 별도의 생성자가 없으며, java.util.regex.Pattern 클래스의 matcher() 메서드를 사용해 객체를 생성하거나 얻을 수 있습니다.
Matcher 클래스의 reset() 메서드는 지금까지 쌓인 모든 상태 정보를 제거하고, 문자 시퀀스를 기본값으로 되돌리며, 추가(append) 위치를 0으로 초기화합니다. 덕분에 새 객체를 만들지 않고도 기존 Matcher를 처음 생성된 것처럼 깨끗한 상태로 재사용할 수 있습니다.
reset() 메서드의 두 가지 형태
- reset() – 인자 없이 호출하며, 원래 입력 시퀀스에 대해 상태 정보만 초기화합니다.
- reset(CharSequence input) – 새로운 문자열을 인자로 받아 입력 시퀀스를 교체하고 상태를 초기화합니다.
예제 1: reset()으로 상태 초기화하기
다음 예제는 HTML 문서에서 <b>(굵은 글씨) 태그로 감싸인 단어들을 정규 표현식으로 찾아낸 뒤, reset() 메서드를 호출해 매처의 상태를 초기화하는 과정을 보여줍니다.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Reset {
public static void main(String[] args) {
String str = "<p>This <b>is</b> an <b>example</b> HTML <b>script</b> where <b>every</b> alternative <b>word</b> is <b>bold</b></p>.";
// 굵은 글씨 태그의 내용을 찾기 위한 정규 표현식
String regex = "<b>(\\S+)</b>";
// Pattern 객체 생성
Pattern pattern = Pattern.compile(regex);
// 컴파일된 패턴을 문자열과 매칭
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println("State of the matcher: " + matcher.toMatchResult());
String result = matcher.group(1);
}
matcher = matcher.reset();
System.out.println("State of the matcher after resetting it: " + matcher.toMatchResult());
}
}
실행 결과
State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,116 lastmatch=<b>is</b>] State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,116 lastmatch=<b>example</b>] State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,116 lastmatch=<b>script</b>] State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,116 lastmatch=<b>every</b>] State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,116 lastmatch=<b>word</b>] State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,116 lastmatch=<b>bold</b>] State of the matcher after resetting it: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,116 lastmatch=]
실행 결과를 보면 find() 메서드가 매칭에 성공할 때마다 lastmatch 정보가 갱신되는 것을 확인할 수 있습니다. 반면 reset() 메서드를 호출한 후에는 lastmatch가 비어 있는 초기 상태로 되돌아간 것을 알 수 있습니다. 즉, 매칭 작업을 처음부터 다시 시작할 준비가 된 것입니다.
예제 2: 새로운 문자열로 리셋하기
reset() 메서드의 또 다른 변형 형태는 문자열 데이터를 인자로 받아, 해당 문자열로 입력 시퀀스를 교체하면서 매처를 리셋합니다. 이렇게 하면 동일한 패턴 객체를 새로운 문자열에 그대로 재사용할 수 있어 효율적입니다.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Reset {
public static void main(String[] args) {
String str = "<p>This <b>is</b> an <b>example</b> HTML <b>script</b> where <b>every</b> alternative <b>word</b> is <b>bold</b></p>.";
// 굵은 글씨 태그의 내용을 찾기 위한 정규 표현식
String regex = "<b>(\\S+)</b>";
// Pattern 객체 생성
Pattern pattern = Pattern.compile(regex);
// 컴파일된 패턴을 문자열과 매칭
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println("State of the matcher: " + matcher.toMatchResult());
String result = matcher.group(1);
}
// 새로운 문자열로 매처 리셋
matcher = matcher.reset("<b>this</b> is <b>new</b> string <b>after</b> reset");
while (matcher.find()) {
System.out.println("State of the matcher after resetting it: " + matcher.toMatchResult());
}
}
}
실행 결과
State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,116 lastmatch=<b>is</b>] State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,116 lastmatch=<b>example</b>] State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,116 lastmatch=<b>script</b>] State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,116 lastmatch=<b>every</b>] State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,116 lastmatch=<b>word</b>] State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,116 lastmatch=<b>bold</b>] State of the matcher after resetting it: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,51 lastmatch=<b>this</b>] State of the matcher after resetting it: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,51 lastmatch=<b>new</b>] State of the matcher after resetting it: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,51 lastmatch=<b>after</b>]
새 문자열("<b>this</b> is <b>new</b> string <b>after</b> reset")이 적용되면서 매칭 영역(region)이 0~51로 변경되었고, this, new, after 세 단어가 순서대로 매칭된 것을 확인할 수 있습니다.
정리
- reset(): 상태 정보를 모두 지우고 원래 입력 시퀀스의 처음부터 다시 매칭을 시작합니다.
- reset(CharSequence input): 입력 시퀀스 자체를 새 문자열로 교체하고 상태를 초기화합니다.
- 두 메서드 모두 Matcher 객체를 반환하므로 필요하다면 메서드 체이닝(method chaining)도 가능합니다.
이처럼 reset() 메서드를 활용하면 하나의 Matcher 객체로 여러 문자열을 반복적으로 처리할 수 있어, 불필요한 객체 생성을 줄이고 성능과 코드 가독성을 모두 높일 수 있습니다.