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

Java 정규식의 \E 메타문자 완벽 이해하기

Java 정규식에서 \E 메타문자는 \Q로 시작된 인용(quoting) 구간을 종료하는 역할을 합니다. \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와 같이 \Q와 \E로 감싸면 결과가 달라집니다. 이 경우 대괄호([ ])가 지닌 문자 클래스 기능이 무효화되어, 정규식은 입력 문자열에서 문자 그대로 '[aeiou]'라는 문자 시퀀스를 찾습니다. 요약하면, 메타문자들이 본래의 의미를 잃고 일반 문자로 처리되는 것입니다.

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 구간은 정규식 내에서 리터럴 텍스트를 안전하게 매칭하고 싶을 때 매우 유용합니다. 특히 사용자 입력을 정규식 패턴에 삽입해야 하는 상황에서 \Q와 \E로 감싸주면 특수 문자로 인한 오동작을 예방할 수 있습니다. 참고로 Java에서는 Pattern.quote(String) 메서드를 사용해도 동일한 효과를 얻을 수 있으며, 이 메서드는 내부적으로 주어진 문자열을 \Q와 \E로 감싸줍니다.