\Z 메타 문자란 무엇인가?
정규 표현식의 서브 표현식이자 메타 문자인 \Z는 허용되는 최종 줄 종결자(line terminator)를 제외한 전체 입력 문자열의 끝과 일치합니다. 쉽게 말해, 문자열 맨 끝에 개행 문자(\n)가 포함되어 있더라도 그 바로 앞 위치에서 매칭이 성공할 수 있습니다.
\z와 \Z의 차이점
Java 정규식에는 비슷하지만 미묘하게 다른 두 가지 끝 경계 메타 문자가 존재합니다.
- \z : 입력 문자열의 정확한 끝에만 일치합니다.
- \Z : 입력 문자열의 끝과 일치하며, 마지막에 줄 종결자가 있다면 그 바로 앞 위치에서도 일치할 수 있습니다.
예제 1: 기본적인 사용법
다음은 특정 단어로 끝나는 문자열을 검사하는 간단한 예제입니다.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[]) {
String regex = "Tutorialspoint\\z";
String input = "Hi how are you welcome to Tutorialspoint";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("Number of matches: " + count);
}
}실행 결과
Number of matches: 1
예제 2: 문자열이 숫자로 끝나는지 확인하기
다음 Java 프로그램은 주어진 입력 텍스트가 숫자로 끝나는지 여부를 검증합니다. 여러 줄로 구성된 문자열이라도 마지막 줄의 끝 부분을 정확하게 확인할 수 있습니다.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Data {
public static void main(String args[]) {
String regex = "[0-9]\\z";
String input = "Hi how are you \n this is sample text \n this is third line 554";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if(m.find()) {
System.out.println("Given input ends with a digit");
} else {
System.out.println("Given input doesn't end with a digit");
}
}
}실행 결과
Given input ends with a digit
정리
\Z(그리고 \z) 메타 문자는 문자열의 끝을 기준으로 패턴을 검사할 때 매우 유용합니다. 파일 확장자 검사, 로그 형식 검증, 사용자 입력 유효성 확인 등 다양한 실무 상황에서 활용할 수 있으며, 줄 종결자를 어떻게 처리할지에 따라 \z와 \Z 중 적절한 것을 선택하면 됩니다.