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

Java 정규식의 점(.) 메타 문자 완벽 가이드

정규식(Regular Expression)에서 점(.)은 가장 기본적이면서도 널리 사용되는 메타 문자입니다. 점(.)은 줄바꿈 문자(newline)를 제외한 모든 단일 문자와 일치합니다.

예를 들어 정규식이 "a.c"라면 "abc", "axc", "a1c"처럼 a와 c 사이에 어떤 문자가 와도 매칭됩니다.

예제 1: 점(.)으로 전체 문자 개수 세기

아래 예제는 점(.) 메타 문자를 사용해 입력 문자열에서 줄바꿈을 제외한 모든 문자와 일치하는 항목의 개수를 세는 프로그램입니다.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchesAll {
    public static void main( String args[] ) {
        String regex = ".";
        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: 40

입력 문자열에는 공백을 포함해 총 40개의 문자가 있으며, 점(.)이 각각의 문자와 일치하므로 40이라는 결과가 출력됩니다.

예제 2: 특정 패턴의 단어 찾기

다음 Java 프로그램은 사용자로부터 5개의 문자열을 입력받고, 그중 e로 끝나는 4글자 단어를 찾아 출력합니다. 여기서 정규식 "...e"는 앞의 세 글자는 어떤 문자든 허용하고 마지막 글자가 e인 경우를 의미합니다.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
    public static void main( String args[] ) {
        String regex = "...e";
        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("four letter words that ends with e: ");
        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:
hive
sample
wife
life
naive
four letter words that ends with e:
hive
wife
life

결과 분석

출력 결과를 보면 "hive", "wife", "life"만 매칭되었습니다. 그 이유는 다음과 같습니다.

  • hive, wife, life: 정확히 4글자이며 마지막 글자가 e이므로 매칭됩니다.
  • sample: 6글자로 길이가 맞지 않아 매칭되지 않습니다.
  • naive: 5글자로 길이가 맞지 않아 매칭되지 않습니다.

이처럼 점(.) 메타 문자를 활용하면 문자 하나하나를 유연하게 매칭할 수 있어, 길이와 형식이 정해진 패턴 검색에 매우 유용합니다.