Use the -match operator to find either string

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Mishaua Mishaua 10 months, 2 weeks ago.

  • Author
    Posts
  • #33744
    Profile photo of Mishaua
    Mishaua
    Participant

    I am trying to figure out how to use the -match string to parse for two phrases to see if either of them match.

     $phrase = "mary had a little lamb and lots of other smaller lambs and pigs and goats" 

    Searching for one string works just fine:

     if ($phrase -match "a little lamb") {$true} else {$false} 

    Is there a way to use two strings with something similar to an -or operator i.e.

    if ($phrase -match "a little lamb" -or "of other smaller lambs") {$true} else {$false} 

    The above example does not seem to work. Even if both of the strings are invalid it still returns true. Any hints on how to do this? I attempted to put the phrases first with the -or operator and then -match to the variable but this still does not work as expected. I have seen other online examples that use a | character between the phrases, but that does not seem to work either (or I am not understanding the regex command). I can just match both phrases separately, and output the results to variables. Comparing both of the variables via an if statement with an -eq operator works. There has got to be an easier lighter method to do this though.

  • #33750
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Well, there are two ways you could do that. If you want to use the PowerShell -or operator, you can, but you have to have a complete clause on both sides:

    if ($phrase -match "a little lamb" -or $phrase -match "of other smaller lambs") {$true} else {$false} 
    

    So you'd be using the -match operator twice. Or, you can use the OR operator in regex (which is a pipe symbol):

    if ($phrase -match "a little lamb|of other smaller lambs") {$true} else {$false} 
    
  • #34074
    Profile photo of Mishaua
    Mishaua
    Participant

    Thanks Dave that worked for me.

You must be logged in to reply to this topic.