search a string for an array of string fragments
I need to search through a string to see if it contains any of the text in an array of strings. For example
excludeList="warning","a common unimportant thing", "something else"
searchString=here is a string telling us about a common unimportant thing.
otherString=something common but unrelated
In this example, we would find the "common unimportant thing" string from the array in my searchList and would return true. however otherString doesn't contain any of the complete strings in the array, so would return false.
Im sure this isnt tha开发者_高级运维t complicated, but I've been looking at it for too long...
Update: The best I can get so far is:
#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++
}
it isnt too elegant though...
You can use a regular expression. The '|' regex character is the equivalent to the OR operator:
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
The function below finds all items contained in the specified string, returning true if any are found.
function ContainsAny( [string]$s, [string[]]$items ) {
$matchingItems = @($items | where { $s.Contains( $_ ) })
[bool]$matchingItems
}
精彩评论