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

Java 정규식(RegEx)으로 단어 경계를 일치시키는 방법

Java 정규식에서는 메타 문자 \b를 사용하여 단어 경계(word boundary)를 일치시킬 수 있습니다.

단어 경계란?

단어 경계란 단어 문자(알파벳, 숫자, 밑줄)와 비단어 문자 사이의 위치를 의미합니다. 즉, \b는 실제 문자가 아닌 위치를 나타내는 앵커(anchor) 역할을 하며, 단어의 시작 또는 끝 지점을 찾을 때 유용하게 사용됩니다.

예제 1: 단어 경계 개수 세기

다음 예제는 입력받은 문자열에서 \b가 일치하는 횟수, 즉 단어 경계의 개수를 계산합니다.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
    public static void main(String args[]) {
        // 사용자로부터 문자열 입력 받기
        System.out.println("문자열을 입력하세요");
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        String regex = "\\b";
        // 정규식 컴파일
        Pattern pattern = Pattern.compile(regex);
        // Matcher 객체 생성
        Matcher matcher = pattern.matcher(input);
        int count = 0;
        while(matcher.find()) {
            count++;
        }
        System.out.println("단어 경계의 개수: "+count);
    }
}

실행 결과

문자열을 입력하세요
this is a sample text
단어 경계의 개수: 10

위 예제에서 입력된 문장에는 5개의 단어가 있으며, 각 단어마다 시작과 끝에 하나씩 경계가 존재하므로 총 10개의 단어 경계가 검출됩니다.

예제 2: 각 단어의 첫 글자 추출하기

\b와 문자 클래스를 조합하면 각 단어의 첫 글자만 추출할 수 있습니다. 아래 예제는 \b[a-zA-Z] 패턴을 사용하여 주어진 문자열에서 각 단어의 첫 글자를 출력합니다.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FirstLetterExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("샘플 텍스트를 입력하세요: ");
        String data = sc.nextLine();
        String regex = "\\b[a-zA-Z]";
        // Pattern 객체 생성
        Pattern pattern = Pattern.compile(regex);
        // Matcher 객체 생성
        Matcher matcher = pattern.matcher(data);
        System.out.println("주어진 문자열에서 각 단어의 첫 글자: ");
        while(matcher.find()) {
            System.out.print(matcher.group()+" ");
        }
    }
}

실행 결과

샘플 텍스트를 입력하세요:
National Intelligence Agency Research & Analysis Wing
주어진 문자열에서 각 단어의 첫 글자:
N I A R A W

이처럼 \b 메타 문자를 활용하면 단어의 시작 위치를 기준으로 원하는 패턴을 정확하게 매칭할 수 있어, 텍스트 분석이나 데이터 추출 작업에서 매우 유용합니다.