Java查找出现的单词

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

解决方法

下面的例子演示了如何使用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 = "aw*";
      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: aw*
MATCH: a test
MATCH: A TEST
原文地址:https://www.cnblogs.com/borter/p/9617145.html