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

Java Pattern 클래스의 quote() 메서드 완벽 정리: 예제 코드로 쉽게 이해하기

Java의 java.util.regex 패키지는 문자 시퀀스에서 특정 패턴을 찾기 위한 다양한 클래스를 제공합니다.

이 패키지의 Pattern 클래스는 정규 표현식(regular expression)을 컴파일한 결과를 나타내는 클래스입니다. 이 클래스가 제공하는 quote() 메서드는 문자열 값을 인자로 받아, 해당 문자열과 정확히 일치하는 패턴 문자열을 반환합니다. 즉, 주어진 문자열에 메타문자(metacharacter)와 이스케이프 시퀀스(escape sequence)가 추가되지만, 문자열 자체의 의미는 그대로 유지됩니다.

쉽게 말해, quote() 메서드는 정규 표현식에서 특별한 의미를 가지는 문자들([, ], ., * 등)을 일반 문자로 취급하도록 만들어 주는 역할을 합니다. 반환되는 패턴 문자열은 \Q\E 사이에 원본 문자열이 감싸인 형태입니다.

예제 1: 사용자 입력으로 quote() 메서드 사용하기

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QuoteExample {
    public static void main( String args[] ) {
        // 문자열 입력 받기
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input string");
        String input = sc.nextLine();
        System.out.print("Enter the string to be searched: ");
        String regex = Pattern.quote(sc.nextLine());
        System.out.println("pattern string: "+regex);
        // 정규 표현식 컴파일
        Pattern pattern = Pattern.compile(regex);
        // Matcher 객체 가져오기
        Matcher matcher = pattern.matcher(input);
        if(matcher.find()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
    }
}

실행 결과

Enter input string
This is an example program demonstrating the quote() method
Enter the string to be searched: the
pattern string: \Qthe\E
Match found

위 예제에서 검색할 문자열 "the"가 Pattern.quote() 메서드를 통해 \Qthe\E 형태의 패턴 문자열로 변환된 것을 확인할 수 있습니다. 이렇게 변환된 패턴은 입력 문자열에서 "the"라는 일반 문자열을 그대로 찾아내며 매칭에 성공합니다.

예제 2: 특수 문자를 포함한 정규 표현식 처리

다음 예제는 대괄호 []처럼 정규 표현식에서 특별한 의미를 가지는 문자가 포함된 경우를 보여줍니다.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QuoteExample {
    public static void main( String args[] ) {
        String regex = "[aeiou]";
        String input = "Hello how are you welcome to Tutorialspoint";
        // 정규 표현식 컴파일
        Pattern.compile(regex);
        regex = Pattern.quote(regex);
        System.out.println("pattern string: "+regex);
        // 정규 표현식 컴파일
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        if(matcher.find()) {
            System.out.println("The input string contains vowels");
        } else {
            System.out.println("The input string does not contain vowels");
        }
    }
}

실행 결과

pattern string: \Q[aeiou]\E
The input string contains vowels

원래 [aeiou]는 모음 중 하나와 일치하는 문자 클래스(character class)입니다. 하지만 quote() 메서드를 적용하면 \Q[aeiou]\E로 변환되어, 대괄호가 더 이상 문자 클래스로 해석되지 않고 [aeiou]라는 문자열 자체와 일치하는 패턴이 됩니다.

quote() 메서드 활용 포인트

  • 사용자 입력 검색: 사용자가 입력한 문자열을 정규 표현식으로 검색할 때, 입력값에 특수 문자가 포함되어 있어도 안전하게 리터럴(literal) 검색이 가능합니다.
  • 메타문자 무력화: 정규 표현식의 특수 문자 기능을 비활성화하고 순수 문자열 비교가 필요할 때 유용합니다.
  • 안전성 향상: 외부 입력값을 그대로 정규 표현식에 사용하면 의도치 않은 동작이 발생할 수 있는데, quote()를 사용하면 이러한 위험을 방지할 수 있습니다.