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