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

Java 정규식 캐럿(^) 메타문자 – 문자열 시작 위치 매칭 완벽 가이드

정규식(Regular Expression)에서 메타문자 "^"(캐럿)는 줄의 시작 위치를 나타냅니다. 패턴 맨 앞에 이 문자를 사용하면, 입력 문자열이 해당 패턴으로 시작하는 경우에만 일치하도록 제한할 수 있습니다. 반대로 "$"는 줄의 끝을 의미하며, 두 문자를 함께 사용하면 문자열 전체가 정확히 해당 패턴과 일치하는지 검사할 수 있습니다.

예제 1 – 문자열 시작 부분 매칭

아래 예제는 정규식 "^Hi how are you"를 사용해 입력 문자열이 "Hi how are you"로 시작하는지 확인하고, 일치 횟수를 출력합니다.

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

public class RegexExample {
   public static void main(String args[]) {
      String regex = "^Hi how are you";
      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

입력 문자열이 "Hi how are you"로 시작하기 때문에 한 번 일치하여 결과가 1로 출력됩니다. 만약 동일한 문구가 문자열 중간에 등장하더라도, 캐럿(^)이 시작 위치를 강제하기 때문에 매칭되지 않습니다.

예제 2 – 숫자로 시작하는 문자열 찾기

다음 Java 프로그램은 사용자로부터 5개의 문자열을 입력받은 뒤, 그중 숫자로 시작하는 문자열만 골라 출력합니다. 정규식 "^[0-9].*$"는 첫 글자가 0~9 사이의 숫자이고, 그 뒤에 임의의 문자들이 이어지는 문자열을 의미합니다.

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

public class StartingwithDigit {
   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 starting 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
11 sample string 3
22 sample string 4
43534 56353 636
Strings starting with digits:
11 sample string 3
22 sample string 4
43534 56353 636

실행 결과를 보면 "sample string 1", "sample string 2"처럼 알파벳으로 시작하는 문자열은 제외되고, "11", "22", "43534"로 시작하는 세 개의 문자열만 출력된 것을 확인할 수 있습니다.

참고 – 캐럿(^)의 다른 용도

  • 부정 문자 클래스: 대괄호 안에서 "[^abc]"처럼 사용하면 a, b, c를 제외한 임의의 문자 하나와 일치합니다.
  • 다중 라인 모드(MULTILINE): Pattern.compile() 시 MULTILINE 플래그를 설정하면 ^가 전체 문자열뿐 아니라 각 줄의 시작 위치와도 일치합니다.