如何找到一个单词的每个出现?

解决方法

下面的例子演示了如何使用Pattern.compile()方法和m.group()方法找到一个词出现次数。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
   public static void main(String args[]) 
   throws Exception {
      String candidate = "this is a test, A TEST.";
      String regex = "\ba\w*\b";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(candidate);
      String val = null; 
      System.out.println("INPUT: " + candidate);
      System.out.println("REGEX: " + regex + "
");
      while (m.find()) {
         val = m.group();
         System.out.println("MATCH: " + val);
      }
      if (val == null) {
         System.out.println("NO MATCHES: ");
      }
   }
}

结果

上面的代码示例将产生以下结果。

INPUT: this is a test ,A TEST.
REGEX: \ba\w*\b
MATCH: a test
MATCH: A TEST

相关文章:

  • 2022-12-23
  • 2021-11-01
  • 2022-02-16
  • 2022-12-23
  • 2022-12-23
  • 2021-09-11
  • 2022-01-27
  • 2021-07-11
猜你喜欢
  • 2022-12-23
  • 2021-06-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案