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

标签 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 
    } 
} 

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

问候

最佳答案

你可以这样做:

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

关于java - 检查字符串是否包含列表中的任何字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58939490/

相关文章:

collections - 比较 Java8 中的 Instants

Java 集合缩减为 Map

java - maven模块,将persistence.xml与Spring连接

java - 根据 array1 的随机项按索引选择 array2 项

java - Hadoop 2.6.0 的 Eclipse 插件

java - 替换 Java 中的默认 DNS 名称解析

java - sqlite 数据库连接 : java. Lang.ClassNotFoundException : org. sqlite.JDBC

java - 访问空组的流时,制作基于 Java 8 groupingBy 的映射 "null safe"

java - 使用 Java Streams 返回单词出现的句子计数和列表

Java 8 Stream API : how to convert a List to a Map<Long, Set> 在列表中有重复的键?