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

Java Matcher toString() 메서드 완벽 정리: 예제 코드와 실행 결과로 배우기

Matcher 클래스 개요

java.util.regex.Matcher 클래스는 정규 표현식(Regular Expression) 패턴에 대해 다양한 매칭(match) 연산을 수행하는 엔진 역할을 하는 클래스입니다. 이 클래스에는 별도의 생성자가 정의되어 있지 않으며, java.util.regex.Pattern 클래스의 matcher() 메서드를 호출하여 Matcher 객체를 생성하고 얻을 수 있습니다.

Matcher 클래스의 toString() 메서드는 현재 매처(matcher) 객체의 상태를 나타내는 문자열 값을 반환합니다. 반환되는 문자열에는 해당 매처에 설정된 정규식 패턴(pattern), 매칭이 수행되는 검색 영역(region), 그리고 마지막으로 일치한 결과(lastmatch) 등의 핵심 정보가 포함되어 있어 디버깅 시 유용하게 활용할 수 있습니다.

예제 코드

다음 예제에서는 사용자로부터 문자열을 입력받아 특수문자(#, %, &, *)의 개수를 세고, 사용된 Matcher 객체를 toString() 메서드로 출력합니다.

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

public class ToStringExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input text: ");
        String input = sc.nextLine();
        String regex = "[#%&*]";

        // Pattern 객체 생성
        Pattern pattern = Pattern.compile(regex);

        // Matcher 객체 생성
        Matcher matcher = pattern.matcher(input);

        int count = 0;
        while (matcher.find()) {
            count++;
        }

        // 특수문자 개수 출력
        System.out.println("The are " + count + " special [# % & *] characters in the given text");

        // Matcher 객체의 문자열 표현 출력
        System.out.println("Following is the string format of the matcher used: \n" + matcher.toString());
    }
}

실행 결과

Enter input text:
Hello# How # are# you *& welcome to T#utorials%point
The are 7 special [# % & *] characters in the given text
Following is the string format of the matcher used:
java.util.regex.Matcher[pattern=[#%&*] region=0,52 lastmatch=]

출력 결과 분석

toString() 메서드가 반환한 문자열을 살펴보면 다음과 같은 정보를 확인할 수 있습니다.

  • pattern=[#%&*]: 해당 Matcher 객체에 적용된 정규식 패턴을 의미합니다.
  • region=0,52: 매칭 연산이 수행되는 입력 문자열의 시작 인덱스(0)와 끝 인덱스(52)를 나타냅니다.
  • lastmatch=: 마지막으로 일치한 문자열 정보를 보여주며, find() 루프가 모두 종료된 후에는 빈 값으로 표시됩니다.

이처럼 toString() 메서드를 활용하면 Matcher 객체의 내부 상태를 한눈에 파악할 수 있어, 정규식 관련 로직을 디버깅하거나 학습할 때 매우 유용합니다.