Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java 정규식의 \Q 메타문자 이스케이프 활용법

정규식에서 \Q\E가 나올 때까지 등장하는 모든 문자를 이스케이프(escape) 처리하는 하위 표현식, 즉 메타문자입니다. 따라서 \Q와 \E 사이에 메타문자를 배치하면 해당 문자들이 가진 특수한 의미가 무시되고 일반 문자로 취급됩니다.

기본 예제: 일반적인 정규식 매칭

예를 들어, 정규식 [aeiou]는 입력 문자열 안에 모음(a, e, i, o, u)이 포함되어 있는지 확인합니다. 아래 예제를 살펴보겠습니다.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleProgram {
    public static void main( String args[] ) {
        String regex = "[aeiou]";
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input string: ");
        String input = sc.nextLine();
        // Pattern 객체 생성
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        if(matcher.find()) {
            System.out.println("Match occurred");
        } else {
            System.out.println("Match not occurred");
        }
    }
}

출력 결과

Enter input string:
sample
Match occurred

위 실행 결과에서 볼 수 있듯이, 입력 문자열 "sample"에는 모음 'a'와 'e'가 포함되어 있으므로 매칭이 성공했습니다.

\Q와 \E로 메타문자 의미 제거하기

그런데 동일한 표현식을 \Q[aeiou]\E 형태로 감싸면 상황이 달라집니다. 이 경우 대괄호([])가 문자 클래스(character class)로 해석되지 않고, 문자열 내부에 실제로 "[aeiou]"라는 문자 시퀀스가 그대로 나타나야만 매칭됩니다.

즉, \Q와 \E 사이에 있는 모든 메타문자는 특별한 기능을 잃고 단순한 일반 문자처럼 처리됩니다.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleProgram {
    public static void main( String args[] ) {
        String regex = "\\Q[aeiou]\\E";
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input string: ");
        String input = sc.nextLine();
        // Pattern 객체 생성
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        if(matcher.find()) {
            System.out.println("Match occurred");
        } else {
            System.out.println("Match not occurred");
        }
    }
}

출력 결과 1

Enter input string:
sample
Match not occurred

입력 문자열 "sample"에는 대괄호로 묶인 "[aeiou]"라는 리터럴 문자열이 존재하지 않으므로 매칭에 실패합니다.

출력 결과 2

Enter input string:
The letters [aeiou] are vowels in English alphabet
Match occurred

반면 입력 문자열에 "[aeiou]"라는 문자열이 그대로 포함되어 있으면 매칭에 성공합니다.

정리

\Q...\E 구문은 사용자 입력값을 정규식 패턴으로 안전하게 변환할 때 특히 유용합니다. 예를 들어 Pattern.quote(String) 메서드도 내부적으로 이 방식을 사용하여 문자열 전체를 리터럴 패턴으로 만들어 줍니다. 메타문자의 특수 기능을 비활성화해야 하는 상황이라면 \Q와 \E를 적극적으로 활용해 보세요.