如何找到每个词的出现?(How to find every occurance of a word?)
优质
小牛编辑
126浏览
2023-12-01
问题描述 (Problem Description)
如何找到每个词的出现?
解决方案 (Solution)
下面的示例演示了如何在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 + "\r\n");
while (m.find()) {
val = m.group();
System.out.println("MATCH: " + val);
}
if (val == null) {
System.out.println("NO MATCHES: ");
}
}
}
结果 (Result)
上面的代码示例将产生以下结果。
INPUT: this is a test, A TEST.
REGEX: \ba\w*\b
MATCH: a