检查字符串是否包含确切的关键字

时间:2018-07-21 12:12:48

标签: java arrays arraylist

我有一个字符串列表。对于每个字符串,我希望查看单词“ joe”是否首次出现。我正在用空格隔开,因为我不想数“ joey”一词。

我当前的代码对单词“ joe”的每次出现进行计数,我如何对其进行编辑,因此它仅对单词的首次出现进行计数,然后移至列表中的下一个字符串。

var defaultData = false;

clientService.getClients(defaultData)
     .then(function (res) {

         //do something

      }).catch(function (err) {

          defaultData = true;

          clientService.getClients(defaultData)
                .then(function (res) {

                 //do something

                }).catch(function (err) {

                    console.log(err)

                });
      });

编辑

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;
}

我希望我的代码为此返回2(每个字符串中都出现了乔)

3 个答案:

答案 0 :(得分:2)

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

匹配单词“ joe”但不匹配“ joey”的正则表达式如下:

\bjoe\b

\b匹配单词的边界,因此整个表达式匹配单词的开头,然后是单词,该单词必须是joe,然后是单词的结尾。

在Java中,可以通过在字符串上使用matches(pattern)方法来实现:

"hello joe, how are you?".matches(".*\\bjoe\\b.*");

请注意,matches函数需要正则表达式匹配整个字符串才能返回true,因此我们必须在开头和结尾添加.*,它将匹配任意数量的任意字符。 (.匹配任意字符,*表示您要匹配前面的子表达式任意次数)

此正则表达式的优点在于,它仍然可以使用标点符号。仅在空格上分割将无法在字符串“ hello joe,你好吗?”中识别出joe。

总结起来,这就是完整的解决方案:

public int countMatches(List<String> comments) {
    int numberOfMatches = 0;
    for (String comment : comments) {
        if (comment.matches(".*\\bjoe\\b.*")) {
            numberOfMatches++;
        }
    }
    return numberOfMatches;
}

如果要匹配任意搜索词,则必须小心,因为某些字符在正则表达式中具有特殊含义。我建议使用Pattern.quoteimport java.util.regex.Pattern;):

String pattern = ".\\b" + Pattern.quote(word) + "\\b.*";

然后,您可以将注释与comment.matches(pattern)匹配。

答案 1 :(得分:0)

在代码中,您只需要在break;行之后添加count++;行。 类似于以下内容:

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++;
                break;
            }
        }
        System.out.println(comment);
    }
    System.out.println("count is " + count);
    return count;
}

答案 2 :(得分:0)

正则表达式也可以使这段代码更短。

eftEnum :: (Enum a, Eq a, Ord a) => a -> a -> [a]
eftEnum a b 
    | a  > b = []
    | a == b = [a]
    | otherwise = a : rest 
        where rest = eftEnum (succ a) b

编辑:

@Paelle的正则表达式稍好一些,请改用public int counter(List<String> comments) { String regex = "(.* )?joe( .*)?"; return (int) comments.stream().filter(s -> s.matches(regex)).count(); }

相关问题