Java의 Pattern 클래스가 제공하는 DOTALL 필드는 정규 표현식에서 dotall 모드를 활성화하는 역할을 합니다. 기본적으로 정규 표현식의 메타 문자인 "."(점)은 줄바꿈 문자(line terminator)를 제외한 모든 문자와 일치합니다.
예제 1 – 기본 동작 확인
먼저 DOTALL 플래그 없이 "." 메타 문자가 어떻게 동작하는지 확인해 보겠습니다.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DOTALL_Example {
public static void main(String args[]) {
String regex = ".";
String input = "this is a sample \nthis is second line";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
System.out.print(matcher.group());
}
System.out.println();
System.out.println("Number of new line characters: \n" + count);
}
}
실행 결과
this is a sample this is second line Number of new line characters: 36
실행 결과를 보면 두 줄의 문장이 한 줄로 이어져 출력되었으며, 매칭된 문자 수는 36개입니다. 이는 dotall 모드가 활성화되지 않은 상태에서 "." 메타 문자가 줄바꿈 문자(\n)를 건너뛰고 나머지 문자들만 매칭했기 때문입니다.
DOTALL 모드란 무엇인가?
DOTALL 모드가 활성화되면 "." 메타 문자는 줄 종결자를 포함한 모든 문자와 일치합니다. 다시 말해, Pattern.compile() 메서드에 플래그 값으로 Pattern.DOTALL을 전달하면 "."이 줄바꿈 문자까지 하나의 대상으로 인식하여 매칭하게 됩니다.
예제 2 – DOTALL 플래그 적용하기
이번에는 Pattern.compile() 호출 시 Pattern.DOTALL을 두 번째 인자로 전달해 보겠습니다.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DOTALL_Example {
public static void main(String args[]) {
String regex = ".";
String input = "this is a sample \nthis is second line";
Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
System.out.print(matcher.group());
}
System.out.println();
System.out.println("Number of new line characters: \n" + count);
}
}
실행 결과
this is a sample this is second line Number of new line characters: 37
이번에는 총 37개의 문자가 매칭되었습니다. Pattern.DOTALL 플래그 덕분에 "." 메타 문자가 줄바꿈 문자(\n)까지 포함하여 매칭했기 때문에, 입력 문자열의 개행 부분도 그대로 출력 결과에 반영된 것을 확인할 수 있습니다.
핵심 정리
- 기본 모드: "."은 줄바꿈 문자를 제외한 모든 문자와 일치합니다.
- DOTALL 모드: "."은 줄바꿈 문자를 포함한 모든 문자와 일치합니다.
- 사용 방법:
Pattern.compile(regex, Pattern.DOTALL)형태로 컴파일 시 플래그를 지정하면 됩니다.
여러 줄로 구성된 텍스트를 정규 표현식으로 처리할 때 줄바꿈 문자까지 함께 다루고 싶다면, DOTALL 필드를 활용하면 간단하게 해결할 수 있습니다.