java - 检查字符串是否包含准确的关键字
问题描述
我有一个字符串列表。对于每个字符串,我希望查看是否第一次出现“joe”这个词。例如,我用空格分隔,因为我不想计算“joey”这个词。
我当前的代码计算单词“joe”的每次出现,我如何编辑它,所以它只计算单词的第一次出现,然后移动到列表中的下一个字符串。
public int counter(List<String> comments) {
int count = 0;
String word = "joe";
for (String comment : comments) {
String a[] = comment.split(" ");
for (int j = 0; j < a.length; j++) {
if (word.equals(a[j])) {
count++;
}
}
System.out.println(comment);
}
System.out.println("count is " + count);
return count;
}
编辑
str.add("the hello my the name is joe the this joe is a test");
str.add("i was walking down joe then suddenly joe said hi");
我希望我的代码为此返回 2(乔已出现在每个字符串中)
解决方案
您可以使用正则表达式来检查整个字符串是否包含该单词,而无需先将其拆分为单个单词。
匹配单词“joe”但不匹配“joey”的正则表达式如下:
\bjoe\b
匹配单词的\b
边界,所以整个表达式匹配单词的开头,然后是单词,它必须是 joe,然后是单词的结尾。
在 Java 中,这可以使用matches(pattern)
String 上的方法来实现:
"hello joe, how are you?".matches(".*\\bjoe\\b.*");
请注意,该matches
函数需要正则表达式匹配整个字符串才能返回 true,因此我们必须.*
在开头和结尾添加,这将匹配任意数量的任意字符。(.
匹配任意字符,*
您想要匹配前面的子表达式任意次数的信号)
这个正则表达式的优点是它仍然适用于标点符号。仅在空格上拆分将无法识别字符串“hello joe, how are you?”中的 joe。
总而言之,这将是整个解决方案:
public int countMatches(List<String> comments) {
int numberOfMatches = 0;
for (String comment : comments) {
if (comment.matches(".*\\bjoe\\b.*")) {
numberOfMatches++;
}
}
return numberOfMatches;
}
如果要匹配任意搜索词,则必须小心,因为某些字符在正则表达式中具有特殊含义。我建议使用Pattern.quote
( import java.util.regex.Pattern;
):
String pattern = ".\\b" + Pattern.quote(word) + "\\b.*";
然后您可以将评论与comment.matches(pattern)
.
推荐阅读
- asp.net-mvc - 使用网络摄像头捕获图像并保存到 MVC 中的数据库
- php - 如何制作 PHP $row ahref?
- vim - 管理 vim syntastic gutter line
- java - java - 将 JSONObject 转换为 HashMap
- passport.js - ValidationError:用户验证失败,转换为字符串的值失败
- scala - Spark:按键分组,分区映射
- ibm-cloud - Watson Assistant 和 Watson Discovery 上的 2 因素身份验证?
- javascript - Laravel 按排序返回数据
- intellij-idea - IntelliJ:Ant 报告一个错误。没有迹象表明哪里或什么失败了
- c# - 简化代码 C# switch 语句