匹配单词的 Java 正则表达式
元字符 "\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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP