匹配單詞的 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