Metacharacter \b จับคู่ขอบเขตคำ (word boundary) คือ ตำแหน่งก่อนตัวอักษรแรก หลังตัวอักษรสุดท้าย และระหว่างตัวอักษรคำกับไม่ใช่ตัวอักษรคำ
เพื่อจับคู่ คำเต็ม ให้ล้อมรอบด้วย \b ทั้งสองข้าง: \btest\b
ตัวอย่าง: นับจำนวนคำว่า "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";
Pattern pattern = Pattern.compile(regex);
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
อธิบาย
\btest\bจับคู่ "test" ที่เป็นคำอิสระ- ไม่จับคู่ "testing", "tested", "contest" เป็นต้น
- Word characters = [a-zA-Z0-9_]
ตัวอย่างเพิ่มเติม
| Regex | จับคู่ | ไม่จับคู่ |
|---|---|---|
\bcat\b | cat, a cat, cat! | category, scatter, cat5 |
\b\d+\b | 123, 42 | 123abc, a123 |
\bjava\b | java, Java | javascript, javanese |
เคสไม่ไว้ใจตัวพิมพ์ (Case Insensitive)
Pattern pattern = Pattern.compile("\\btest\\b", Pattern.CASE_INSENSITIVE);