java - 检查字符串是否包含列表中的任何字符串
问题描述
我对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()) {
//
}
推荐阅读
- javascript - 重新排列 json 文件
- matlab - 振动分析科学实验室
- c# - 当我点击逃生时,暂停菜单不会激活
- python - 如何在字典 python 中使用 */+- 等运算符和字符串?
- javascript - Select2 多个值(标签)
- java - 如何解决有关环境变量的启动 PyCharm 的错误不指向有效的 JVM 安装?
- android - Editext 出现时隐藏在键盘后面
- laravel - “.../storage/logs”中没有现有目录,无法创建:只读文件系统
- javascript - 我如何对本机清理功能做出反应?
- c++ - 如何显示我输入到文本文件中的所有数据?