4

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

2
  • I think I might have to do this in a loop one element at a time, but need to use a like statement I cant get working with an array element, see code below #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" #check if the message contains anything from the secondary list $testString -like "$arrColors[0]" $testString -like "blue" $test2 -contains $arrColors[0] Commented Sep 28, 2010 at 20:08
  • the above returns False True True Why doesnt the $testString -like "$arrColors[0]" return true? Commented Sep 28, 2010 at 20:12

2 Answers 2

10

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
Sign up to request clarification or add additional context in comments.

1 Comment

Just an addtion to your answer - if the $excludeList is an array, I would use ($excludeList | % { [regex]::escape($_) } ) -join "|" to turn it into proper regular expression.
3

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.