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

예제로 배우는 Java Matcher hasTransparentBounds() 메서드 완벽 가이드

java.util.regex.Matcher 클래스는 다양한 매칭 작업을 수행하는 엔진 역할을 합니다. 이 클래스에는 별도의 생성자가 없으며, java.util.regex.Pattern 클래스의 matcher() 메서드를 통해 객체를 생성할 수 있습니다.

정규 표현식에서 lookbehind(후방 탐색)lookahead(전방 탐색) 구문은 특정 패턴의 앞이나 뒤에 위치한 패턴을 검사할 때 사용됩니다. 예를 들어 6~10자 사이의 문자열만 허용하려면 아래와 같은 정규 표현식을 사용할 수 있습니다.

"\\A(?=\\w{6,10}\\z)"

기본적으로 매처(matcher) 영역의 경계는 lookahead, lookbehind, 경계 매칭(boundary matching) 구문에 대해 투명하지 않습니다(opaque). 즉, 이러한 구문은 영역(region) 경계 바깥의 입력 내용을 참조할 수 없습니다.

Matcher 클래스의 hasTransparentBounds() 메서드는 현재 매처가 투명한 경계(transparent bounds)를 사용하는지 확인합니다. 투명한 경계를 사용 중이면 true, 아니면 false를 반환합니다.

예제 1 – 비투명 경계(기본값) 상태

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

public class HasTransparentBounds {
    public static void main(String[] args) {
        // 6~10자 문자열을 허용하는 정규 표현식
        String regex = "\\A(?=\\w{6,10}\\z)";
        System.out.println("Enter 5 to 12 characters: ");
        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");
        }
        boolean bool = matcher.hasTransparentBounds();
        if (bool) {
            System.out.println("Current matcher uses transparent bounds");
        } else {
            System.out.println("Current matcher user non-transparent bound");
        }
    }
}

실행 결과

Enter 5 to 12 characters:
sampletext
Match not found
Current matcher user non-transparent bound

영역을 인덱스 0~4로 제한하면 lookahead 내부의 \w{6,10}이 영역 안의 4글자(samp)만 볼 수 있어 길이 조건을 충족하지 못하고 매칭에 실패합니다. 또한 기본값이 비투명 경계이므로 hasTransparentBounds()false를 반환합니다.

예제 2 – 투명 경계로 전환

useTransparentBounds(true)를 호출하면 lookahead 구문이 영역 경계를 넘어 전체 입력을 참조할 수 있습니다.

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

public class HasTransparentBounds {
    public static void main(String[] args) {
        // 6~10자 문자열을 허용하는 정규 표현식
        String regex = "\\A(?=\\w{6,10}\\z)";
        System.out.println("Enter 5 to 12 characters: ");
        String input = new Scanner(System.in).next();
        // Pattern 객체 생성
        Pattern pattern = Pattern.compile(regex);
        // Matcher 객체 생성
        Matcher matcher = pattern.matcher(input);
        // 입력 문자열에 영역(region) 설정
        matcher.region(0, 4);
        // 투명한 경계로 전환
        matcher.useTransparentBounds(true);
        if (matcher.find()) {
            System.out.println("Match found");
        } else {
            System.out.println("Match not found");
        }
        boolean bool = matcher.hasTransparentBounds();
        if (bool) {
            System.out.println("Current matcher uses transparent bounds");
        } else {
            System.out.println("Current matcher user non-transparent bound");
        }
    }
}

실행 결과

Enter 5 to 12 characters:
sampletext
Match found
Current matcher uses transparent bounds

투명한 경계를 사용하면 lookahead가 영역 밖의 나머지 문자열까지 확인할 수 있어, 전체 입력 sampletext(10자)가 길이 조건을 만족하게 되고 매칭에 성공합니다. 이처럼 hasTransparentBounds()는 현재 경계 설정 상태를 간편하게 확인할 때 유용하게 활용됩니다.