簡體   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