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

更新於: 13-1 月-2020

2 千次+ 瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.