Word Boundary \b
Metacharacter \b khớp ranh giới từ: trước ký tự đầu, sau ký tự cuối, và giữa từ/không-từ.
Để khớp từ nguyên vẹn "test": \\btest\\b
Ví dụ: Đếm từ "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("Nhập văn bản: ");
String input = sc.nextLine();
String regex = "\\btest\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Số lần xuất hiện từ 'test': " + count);
}
}
Kết quả
Nhập văn bản: sample data: test test test
Số lần xuất hiện từ 'test': 3
Giải thích
- Khớp:
test(đứng riêng),test.(trước dấu chấm) - Không khớp:
testing,atest,test123
Lưu ý
- Trong Java string literal, backslash phải escape:
"\\btest\\b" \bxem ký tự word: [a-zA-Z0-9_]. Ký tự khác (dấu câu, khoảng trắng) là non-word.- Unicode: dùng
Pattern.UNICODE_CHARACTER_CLASSđể \b hỗ trợ tiếng Việt.