检查字符串是否包含列表中的任何字符串

时间:2019-11-19 17:12:47

标签: java java-stream

我对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 
    } 
} 

有人可以给我一些建议/帮助吗?

致谢

1 个答案:

答案 0 :(得分:3)

您可以这样做:

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()) {
    //
}