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

Java MatchResult end() 메서드 완벽 가이드 – 예제 코드로 배우기

java.util.regex.MatchResult 인터페이스는 정규식 매칭 결과를 조회할 수 있는 다양한 메서드를 제공합니다.

이 인터페이스의 객체는 Matcher 클래스의 toMatchResult() 메서드를 통해 얻을 수 있습니다. 이 메서드는 현재 매처(matcher)의 매칭 상태를 나타내는 MatchResult 객체를 반환합니다.

MatchResult 인터페이스의 end() 메서드는 마지막으로 매칭된 문자열이 끝난 위치의 오프셋(offset)을 반환합니다. 즉, 매칭된 마지막 문자 바로 다음 인덱스 값을 알려줍니다.

end() 메서드 예제

import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
    public static void main( String args[] ) {
        String regex = "you$";
        //사용자로부터 입력 받기
        Scanner sc = new Scanner(System.in);
        String input = "Hello how are you";
        //Pattern 클래스 객체 생성
        Pattern pattern = Pattern.compile(regex);
        //Matcher 클래스 객체 생성
        Matcher matcher = pattern.matcher(input);
        //매칭 여부 확인
        if(matcher.find()) {
            System.out.println("Match found");
        }
        MatchResult res = matcher.toMatchResult();
        int end = res.end();
        System.out.println(end);
    }
}

실행 결과

Enter input text:
hello how are you
Match found
17

위 예제에서 정규식 you$는 문자열 끝에 있는 "you"와 매칭됩니다. 입력 문자열 "Hello how are you"에서 "you"는 인덱스 15부터 시작해 인덱스 16에서 끝나므로, end() 메서드는 그 다음 위치인 17을 반환합니다.