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

Java Pattern.LITERAL 필드란? 예제로 배우는 리터럴 매칭 방법


Pattern.LITERAL 필드란?

java.util.regex.Pattern 클래스의 LITERAL 필드는 패턴을 문자 그대로(literal) 해석하도록 지정하는 컴파일 플래그입니다. 이 옵션이 활성화되면 이스케이프 시퀀스와 메타 문자를 포함한 모든 문자가 더 이상 특별한 의미를 갖지 않으며, 일반 문자처럼 취급됩니다.

예를 들어, 일반적인 경우 정규 표현식 ^This로 입력 텍스트를 검색하면 "This"라는 단어로 시작하는 줄과 일치합니다. 하지만 LITERAL 모드에서는 ^가 '줄의 시작'을 뜻하는 메타 문자로 동작하지 않고, 문자 '^' 그 자체와 일치하게 됩니다.

예제 1: LITERAL 모드로 패턴 검색하기

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LITERAL_Example {
    public static void main(String[] args) {
        String input = "This is the first line\n"
            + "This is the second line\n"
            + "^This is the third line";
        // 문자열 시작 위치를 나타내는 정규 표현식
        String regex = "^This";
        // LITERAL 플래그를 적용하여 Pattern 객체 생성
        Pattern pattern = Pattern.compile(regex, Pattern.LITERAL);
        // Matcher 객체 생성
        Matcher matcher = pattern.matcher(input);
        int count = 0;
        while (matcher.find()) {
            count++;
            System.out.println(matcher.group());
        }
        System.out.println("Number of matches: " + count);
    }
}

출력 결과

^This
Number of matches: 1

리터럴 모드에서는 메타 문자 "^"가 아무런 특수 의미를 갖지 않습니다. 따라서 정규 표현식 "^This"는 '^' 문자가 실제로 포함된 부분, 즉 세 번째 줄의 "^This"와만 일치합니다.

예제 2: 입력 데이터와 함께 결과 확인하기

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LITERAL_Example {
    public static void main(String[] args) {
        String input = "This is the first line\n"
            + "This is the second line\n"
            + "^This is the third line";
        String regex = "^This";
        // LITERAL 플래그를 적용하여 Pattern 객체 생성
        Pattern pattern = Pattern.compile(regex, Pattern.LITERAL);
        System.out.println("입력 문자열:\n" + input);
        // Matcher 객체 생성
        Matcher matcher = pattern.matcher(input);
        int count = 0;
        while (matcher.find()) {
            count++;
            System.out.println(matcher.group());
        }
        System.out.println("Number of matches: " + count);
    }
}

출력 결과

입력 문자열:
This is the first line
This is the second line
^This is the third line
^This
Number of matches: 1

실행 결과를 보면 입력 문자열에 "This"로 시작하는 줄이 두 개 있음에도 불구하고, LITERAL 모드에서는 '^' 문자가 포함된 "^This" 하나만 매칭된 것을 확인할 수 있습니다. 이처럼 Pattern.LITERAL은 정규 표현식 문법을 무시하고 순수한 문자열 검색이 필요할 때 매우 유용하게 활용할 수 있습니다.