下面的示例基于您的评论。它使用关键字列表,它将使用单词边界在给定的字符串中进行搜索。它使用Apache Commons Lang的StringUtils构建正则表达式并打印匹配的组。
String text = "I will come and meet you at the woods 123woods and all the woods";
List tokens = new ArrayList();
tokens.add("123woods");
tokens.add("woods");
String patternString = "\\b(" + StringUtils.join(tokens, "|") + ")\\b";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
如果您正在寻找更高的性能,可以看看StringSearch:Java中的高性能模式匹配算法。
|