在字符串中搜索字符串片段数组

lee*_*lee 3 powershell

我需要搜索一个字符串,看它是否包含字符串数组中的任何文本.例如

excludeList ="警告","一个常见的不重要的事情","别的东西"

searchString =这是一个字符串告诉我们一个常见的不重要的事情.

otherString =常见但不相关的东西

在这个例子中,我们会在searchList中的数组中找到"常见的不重要的东西"字符串,并返回true.但是otherString不包含数组中的任何完整字符串,因此返回false.

我确定这不复杂,但我已经看了太久了......

更新:到目前为止我能做的最好的是:

#list of excluded terms
$arrColors = "blue", "red", "green", "yellow", "white", "pink", "orange", "turquoise"

#the message of the event we've pulled
$testString = "there is a blue cow over there"
$test2="blue"
$count=0
#check if the message contains anything from the secondary list
$arrColors | ForEach-Object{
    echo $count
    echo $testString.Contains($arrColors[$count])
    $count++

}
Run Code Online (Sandbox Code Playgroud)

它虽然太优雅了......

Sha*_*evy 9

您可以使用正则表达式.'|' 正则表达式字符相当于OR运算符:

PS> $excludeList="warning|a common unimportant thing|something else"
PS> $searchString="here is a string telling us about a common unimportant thing."
PS> $otherString="something common but unrelated"

PS> $searchString -match $excludeList
True

PS> $otherString -match $excludeList
False
Run Code Online (Sandbox Code Playgroud)

  • 只是你的答案的一个补充 - 如果`$ excludeList`是一个数组,我会使用`($ excludeList |%{[regex] :: escape($ _)})-join"|"`将它变成正确的正则表达式. (3认同)