java.util.regex.Matcher 클래스는 정규식 기반의 다양한 매칭 작업을 수행하는 엔진 역할을 하는 클래스입니다. 이 클래스는 별도의 생성자를 제공하지 않으며, java.util.regex.Pattern 클래스의 matcher() 메서드를 호출하여 Matcher 객체를 얻을 수 있습니다.
Matcher 클래스가 제공하는 matches() 메서드와 find() 메서드는 모두 입력 문자열에서 정규식 패턴에 일치하는 부분을 찾는다는 공통점이 있습니다. 매치가 존재하면 두 메서드 모두 true를 반환하고, 매치를 찾지 못하면 false를 반환합니다.
matches()와 find()의 핵심 차이
두 메서드의 가장 큰 차이는 매칭을 시도하는 범위입니다.
matches() 메서드는 입력 문자열의 전체 영역(region)이 패턴과 완전히 일치해야만 true를 반환합니다. 예를 들어 여러 줄로 된 텍스트에서 숫자를 검색하는 경우, 패턴이 입력 전체와 일치하지 않으면 결과는 false가 됩니다. 아래 예제에서 정규식 (.*)(\d+)(.*)은 기본적으로 줄바꿈 문자(\n)를 포함하지 않기 때문에, 여러 줄로 구성된 입력 전체와는 일치하지 않습니다.
예제 1: matches() 사용
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String regex = "(.*)(\\d+)(.*)";
String input = "This is a sample Text, 1234, with numbers in between. "
+ "\n This is the second line in the text "
+ "\n This is third line in the text";
// 패턴 객체 생성
Pattern pattern = Pattern.compile(regex);
// Matcher 객체 생성
Matcher matcher = pattern.matcher(input);
if(matcher.matches()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}출력 결과
Match not found
반면 find() 메서드는 입력 문자열 내에서 패턴과 일치하는 다음 부분 문자열(subsequence)을 순차적으로 검색합니다. 즉, 전체가 아니라 영역 안에 단 하나의 매치라도 존재하면 true를 반환합니다.
아래 예제에서는 같은 입력과 같은 정규식을 사용하지만, 숫자가 포함된 첫 번째 줄을 찾아내므로 매치에 성공합니다.
예제 2: find() 사용
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String regex = "(.*)(\\d+)(.*)";
String input = "This is a sample Text, 1234, with numbers in between. "
+ "\n This is the second line in the text "
+ "\n This is third line in the text";
// 패턴 객체 생성
Pattern pattern = Pattern.compile(regex);
// Matcher 객체 생성
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}출력 결과
Match found
정리: 한눈에 보는 matches() vs find()
| 구분 | matches() | find() |
|---|---|---|
| 매칭 범위 | 입력 문자열 전체 | 문자열 내 일부(부분 문자열) |
| 반환 조건 | 전체가 패턴과 일치할 때만 true | 하나라도 일치하면 true |
| 호출 반복 | 반복 호출 시 항상 처음부터 검사 | 호출할 때마다 다음 매치를 검색 |
| 주요 용도 | 입력값 형식 전체 검증 (예: 이메일, 전화번호) | 텍스트에서 특정 패턴 추출·탐색 |
결론적으로, 입력 문자열이 정규식과 완전히 일치하는지 검증하려면 matches()를, 문자열 안에서 패턴에 해당하는 부분을 찾거나 추출하려면 find()를 사용하는 것이 적절합니다.