메타 문자 "\b"는 단어 경계와 일치합니다. 즉, 첫 번째 단어 앞과 마지막 단어 문자 이후, 단어와 비단어 문자 사이에서 일치합니다.
따라서 전체 단어를 일치시키려면 단어 경계 메타 문자 사이를 -
로 둘러싸야 합니다.\btest\b
예시
다음 Java 예제는 주어진 입력 문자열에서 test라는 단어의 발생 횟수를 계산하고 인쇄합니다.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "\\btest\\b";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
int count =0;
while (matcher.find()) {
count++;
}
System.out.println("Number of occurrences of the word test : "+count);
}
} 출력
Enter input text: sample data: test test test Number of occurrences of the word test : 3