Pattern.MULTILINE은 Java 정규식에서 여러 줄(multiline) 모드를 활성화하는 필드입니다.
일반적으로 ^와 $ 메타 문자는 입력 문자열의 줄 수와 관계없이 전체 입력의 시작과 끝에만 일치합니다. 하지만 MULTILINE 플래그를 사용하면 각 줄의 시작과 끝을 개별적으로 인식하게 됩니다.
예제 1: 기본 동작 (플래그 없음)
아래 예제는 플래그 없이 ^([0-9]+).* 패턴으로 숫자로 시작하는 줄을 찾습니다.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MULTILINE_Example {
public static void main(String args[]) {
String input = "2234 This is a sample text\n"
+ "1424 This second 2335 line\n"
+ "This id third 455 line\n"
+ "Welcome to Tutorialspoint\n";
Pattern pattern = Pattern.compile("^([0-9]+).*");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
}
}실행 결과
2234
플래그를 지정하지 않으면 전체 입력 시퀀스가 하나의 단일 문자열로 취급됩니다. 따라서 ^ 메타 문자는 전체 입력의 맨 처음에만 일치하며, 결과적으로 첫 번째 줄의 숫자인 2234만 출력됩니다.
예제 2: Pattern.MULTILINE 적용
이번에는 compile() 메서드에 두 번째 인자로 Pattern.MULTILINE 플래그를 전달합니다.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MULTILINE_Example {
public static void main(String args[]) {
String input = "2234 This is a sample text\n"
+ "1424 This second 2335 line\n"
+ "This id third 455 line\n"
+ "Welcome to Tutorialspoint\n";
Pattern pattern = Pattern.compile("^([0-9]+).*", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
}
}실행 결과
2234 1424
MULTILINE 플래그가 적용되면 ^와 $ 메타 문자가 각 줄(line)의 시작과 끝에 일치합니다. 그 결과 숫자로 시작하는 두 줄(2234, 1424)이 모두 매칭됩니다. 세 번째 줄은 숫자로 시작하지 않고 네 번째 줄도 숫자가 없으므로 제외됩니다.
정리
- 플래그 미사용:
^와$가 전체 입력의 시작과 끝에만 일치 - Pattern.MULTILINE 사용: 각 줄의 시작과 끝에 개별적으로 일치
- 비트 연산자
|(OR)를 사용해Pattern.CASE_INSENSITIVE등 다른 플래그와 조합할 수 있습니다.