Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search a string for an array of string fragments

Tags:

powershell

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 that 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...

like image 833
lee Avatar asked Dec 13 '22 19:12

lee


2 Answers

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
like image 107
Shay Levy Avatar answered Jan 07 '23 08:01

Shay Levy


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
}
like image 44
Emperor XLII Avatar answered Jan 07 '23 09:01

Emperor XLII