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

예제로 배우는 Java Matcher region(int start, int end) 메소드 완벽 가이드


java.util.regex.Matcher 클래스는 입력 문자열에 대해 다양한 매칭 연산을 수행하는 엔진 역할을 합니다. 이 클래스는 별도의 생성자를 제공하지 않으며, java.util.regex.Pattern 클래스의 matcher() 메소드를 사용하여 객체를 생성할 수 있습니다.

Matcher 클래스의 region() 메소드는 입력 문자열에서 시작 위치와 끝 위치를 나타내는 두 개의 정수 값을 인자로 받아, 현재 매처(matcher)가 검색할 영역(region)을 설정합니다. 이 메소드를 사용하면 전체 문자열이 아닌 특정 구간에서만 패턴 매칭을 수행할 수 있어, 긴 텍스트에서 원하는 부분만 효율적으로 검사할 때 매우 유용합니다.

예제 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionExample {
    public static void main(String[] args) {
        // 6~10자의 단어를 허용하는 정규 표현식
        String regex = "\\A(?=\\w{6,10}\\z)";
        System.out.println("5~12자의 문자열을 입력하세요: ");
        String input = new Scanner(System.in).next();
        // Pattern 객체 생성
        Pattern pattern = Pattern.compile(regex);
        // Matcher 객체 생성
        Matcher matcher = pattern.matcher(input);
        // 입력 문자열에 영역(region) 설정
        matcher.region(0, 4);
        if(matcher.find()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
    }
}

실행 결과

5~12자의 문자열을 입력하세요:
sampleText
Match not found

위 예제에서는 region(0, 4)을 호출하여 입력 문자열의 처음 4글자("samp")만 검색 대상으로 지정했습니다. 그런데 정규 표현식은 6~10자의 단어를 요구하기 때문에, 4글자 범위 안에서는 조건을 만족하는 항목을 찾을 수 없어 "Match not found"가 출력됩니다. 이처럼 region() 메소드는 매칭 범위를 제한하여 결과에 직접적인 영향을 줍니다.

예제 2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegionExample {
    public static void main(String[] args) {
        String regex = "(.*)(\\d+)(.*)";
        String input = "This is a sample Text, 1234, with numbers in between.";
        // Pattern 객체 생성
        Pattern pattern = Pattern.compile(regex);
        // Matcher 객체 생성
        Matcher matcher = pattern.matcher(input);
        // 매처의 영역(region) 설정
        matcher.region(0, 20);
        if(matcher.matches()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
    }
}

실행 결과

Match not found

두 번째 예제에서는 region(0, 20)으로 검색 범위를 문자열의 앞 20글자까지로 한정했습니다. 이 범위에 해당하는 "This is a sample Te"에는 숫자가 포함되어 있지 않으므로, 숫자(\\d+)를 찾는 정규 표현식과 일치하지 않아 "Match not found"가 출력됩니다. 만약 region을 설정하지 않고 전체 문자열을 대상으로 했다면, 중간에 있는 "1234" 때문에 매칭에 성공했을 것입니다.

함께 알아두면 좋은 메소드

region() 메소드와 함께 다음 메소드들을 활용하면 더욱 편리합니다.

  • regionStart(): 현재 설정된 영역의 시작 인덱스를 반환합니다.
  • regionEnd(): 현재 설정된 영역의 끝 인덱스를 반환합니다.
  • transparentBounds(boolean): 영역 경계 밖의 문자를 lookaround 전후 탐색에서 참조할지 여부를 설정합니다.

이처럼 region() 메소드를 적절히 활용하면 대용량 텍스트 처리 시 불필요한 검색 범위를 줄여 성능을 개선하고, 원하는 구간만 정밀하게 패턴 매칭을 수행할 수 있습니다.