首页 > 解决方案 > 检查字符串是否包含准确的关键字

问题描述

我有一个字符串列表。对于每个字符串,我希望查看是否第一次出现“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(乔已出现在每个字符串中)

标签: javaarraysarraylist

解决方案


您可以使用正则表达式来检查整个字符串是否包含该单词,而无需先将其拆分为单个单词。

匹配单词“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).


推荐阅读