匹配单词的 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.