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

Java 정규식 $ (달러) 메타 문자 – 문자열 끝 매칭 완벽 가이드

정규식에서 $ 메타 문자란?

Java 정규식에서 하위 표현식이자 메타 문자인 $한 줄의 끝을 나타냅니다. 즉, 패턴 뒤에 $를 붙이면 해당 패턴으로 끝나는 문자열만 매칭됩니다.

예를 들어 정규식 Tutorialspoint$는 "Hi how are you welcome to Tutorialspoint"처럼 Tutorialspoint로 끝나는 문자열과 일치하지만, 중간에 등장하는 경우에는 매칭되지 않습니다.

예제 1 – 문자열 끝 패턴 확인하기

다음 예제는 입력 문자열이 지정한 패턴으로 끝나는지 확인하고, 매칭된 횟수를 출력합니다.

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

public class EndWith {
    public static void main(String args[]) {
        String regex = "Tutorialspoint$";
        String input = "Hi how are you welcome to Tutorialspoint";

        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);

        int count = 0;
        while (m.find()) {
            count++;
            System.out.println("Number of matches: " + count);
        }
    }
}

실행 결과

Number of matches: 1

입력 문자열이 "Tutorialspoint"로 끝나기 때문에 정확히 1번 매칭됩니다.

예제 2 – 숫자로 끝나는 문자열 걸러내기

아래 프로그램은 사용자로부터 5개의 문자열을 입력받은 뒤, 숫자로 끝나는 문자열만 골라 출력합니다. 여기서 사용된 정규식 ^.*[0-9]$는 다음과 같이 해석할 수 있습니다.

  • ^ : 문자열의 시작
  • .* : 임의의 문자가 0개 이상 반복
  • [0-9] : 숫자 하나
  • $ : 문자열의 끝
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EndingwithDigit {
    public static void main(String args[]) {
        String regex = "^.*[0-9]$";

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter 5 input strings: ");

        String input[] = new String[5];
        for (int i = 0; i < 5; i++) {
            input[i] = sc.nextLine();
        }

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

        System.out.println("Strings ending with digits: ");
        for (int i = 0; i < 5; i++) {
            // Matcher 객체 생성
            Matcher m = p.matcher(input[i]);
            if (m.matches()) {
                System.out.println(m.group());
            }
        }
    }
}

실행 결과

Enter 5 input strings:
sample string 1
sample string 2
test data
hello
3264533 3546373 7653

Strings ending with digits:
sample string 1
sample string 2
3264533 3546373 7653

참고 사항

$ 메타 문자는 기본적으로 전체 입력의 마지막 또는 개행 문자( ) 바로 앞에서 매칭됩니다. 만약 여러 줄로 구성된 텍스트에서 각 줄의 끝을 기준으로 매칭하고 싶다면, Pattern.MULTILINE 플래그를 함께 사용하면 됩니다.