首页 > 解决方案 > 检查字符串是否包含列表中的任何字符串

问题描述

我对java很陌生,目前卡住了,不知道如何继续。

我想要做的是检查一个字符串是否包含单词列表中的任何单词,如果是则输出它们。

在我的情况下,所有字符串都将具有类似的文本(例如 5 分钟):

Set timer to five minutes

或者这个:

Timer five minutes

这是我当前的代码,带有一些我想要做的评论:

import java.util.stream.Stream; 

class GFG { 

// Driver code 
public static void main(String[] args) 
{ 

String example = Set timer to five minutes

    Stream<String> stream = Stream.of(("Timer", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten") //The stream/array would be much bigger since I want to cover every number till 200 

//Now I thought I can use stream filter to check if example contains the word Timer and any of the words of the Stream and if it does I want to use the output to trigger something else

    if(stream.filter(example -> example .contains(NOTSUREWHATTOPUTHERE))) {
       //If detected that String contains Timer and Number, then create timer 
    } 
} 

谁能给我一些建议/帮助?

问候

标签: javajava-stream

解决方案


你可以这样做:

String[] words = { "Timer", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" };

String example = "Set timer to five minutes";

String exLower = example.toLowerCase();
if (Stream.of(words).anyMatch(word -> exLower.contains(word.toLowerCase()))) {
    //
}

即使单词有不同的大写/小写,该代码至少会正确检查,但如果文本中嵌入了另一个单词,则它会失败,例如文本"stone"将匹配,因为"one"找到了。

要解决这个问题,“最简单”的方法是将单词列表转换为正则表达式。

String[] words = { "Timer", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" };

String example = "Set timer to five minutes";

String regex = Stream.of(words).map(Pattern::quote)
        .collect(Collectors.joining("|", "(?i)\\b(?:", ")\\b"));
if (Pattern.compile(regex).matcher(example).find()) {
    //
}

推荐阅读