繁体   English   中英

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

[英]Check if a string contains any of the strings from an List

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

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

在我的情况下,所有字符串都将具有类似的文本(例如 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 
    } 
} 

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

问候

你可以这样做:

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

正确的应该是

String example = "Set timer to five minutes";
Stream<String> stream = Stream.of("Timer", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten");
if (stream.anyMatch(something -> example.contains(something))) {

}

您应该为 lambda 变量指定一个不同于example的名称,因为这与已经存在的局部变量冲突。
此外,您可以/应该使用anyMatch而不是filter + 检查长度。

要不就:

if (stream.anyMatch(example::contains)) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM