Java 정규 표현식에서 \b 메타 문자는 단어 경계(word boundary)를 의미합니다. 이 메타 문자를 활용하면 입력 문자열에서 특정 단어가 독립적인 단어로 존재하는지 정확하게 확인할 수 있습니다.
특정 단어를 찾고 싶다면 정규 표현식에서 찾으려는 단어 앞뒤를 단어 경계로 감싸주면 됩니다.
"\\b찾을단어\\b";
이렇게 하면 해당 단어가 다른 단어의 일부(부분 문자열)가 아닌, 완전한 하나의 단어로 매칭됩니다. 예를 들어 "hello"를 검색할 때 "helloworld"나 "sayhello"에는 매칭되지 않고, 독립된 "hello"라는 단어에만 매칭됩니다.
예제 1: 사용자 입력에서 단어 찾기
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchingWordExample1 {
public static void main(String args[]) {
// 문자열 값 읽기
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string");
String input = sc.next();
// 특정 단어를 찾기 위한 정규 표현식
String regex = "\\bhello\\b";
// 정규 표현식 컴파일
Pattern pattern = Pattern.compile(regex);
// Matcher 객체 생성
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}실행 결과
Enter input string hello welcome to Tutorialspoint Match found
예제 2: 여러 줄 문자열에서 단어 찾기
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample2 {
public static void main(String args[]) {
String input = "This is sample text \n "
+ "This is second line "
+ "This is third line";
String regex = "\\bsecond\\b";
// 정규 표현식 컴파일
Pattern pattern = Pattern.compile(regex);
// Matcher 객체 생성
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}실행 결과
Match found
핵심 포인트 정리
- Pattern.compile(regex): 문자열 형태의 정규 표현식을 Pattern 객체로 컴파일합니다.
- pattern.matcher(input): 대상 문자열에 대해 매칭 작업을 수행할 Matcher 객체를 생성합니다.
- matcher.find(): 입력 문자열 내에서 패턴과 일치하는 부분이 있는지 확인하고, 존재하면 true를 반환합니다.
- \b: 단어 경계를 나타내며, 부분 문자열이 아닌 완전한 단어 단위의 매칭을 보장합니다.
이처럼 Pattern 클래스와 \b 메타 문자를 조합하면 문자열에서 원하는 단어를 간단하고 정확하게 검색할 수 있습니다.