元字符“ \ 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";
//创建一个模式对象
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