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

时间:2010-09-28 20:04:52

标签: 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++

}

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

下面的函数查找指定字符串中包含的所有项目,如果找到则返回true。

function ContainsAny( [string]$s, [string[]]$items ) {
  $matchingItems = @($items | where { $s.Contains( $_ ) })
  [bool]$matchingItems
}
相关问题