1

I need to match a content of a string against set of strings. I have something like this:

>$ID = "GEt"
>$ID -Match  "Get|YES|NO"
True

I don't need -cmatch - that's alright. But the following - not:

>$ID = "targetService"
>$ID -Match  "Get|YES|NO"
True

How do I avoid that, if the string I'm looking for is a substring of another?

2
  • 3
    "get","yes","no" -contains $ID Commented Jul 8, 2016 at 13:07
  • Issue? No! This is REGEEEEEX! Seriously, you should read a little about regex and matches in powershell. Commented Jul 8, 2016 at 14:17

2 Answers 2

2

You can force an exact match with an alternating regex by adding the begin and end line anchors (^ and $). Use a non-capturing group to isolate the alternated text from the anchors:

$ID = "targetService"
$ID -Match  '^(?:Get|YES|NO)$'

False
Sign up to request clarification or add additional context in comments.

Comments

1

As indicated in the comments, a regex -match operation is not necessary when you're looking for an exact match among a set of strings. Simply use the -contains operator (or -in in PowerShell 3.0+):

PS C:\> $ID = "GEt"
PS C:\> $Options = "get","yes","no"
PS C:\> $Options -contains $ID
True
PS C:\> $ID -in $Options
True
PS C:\> $ID = "targetService"
PS C:\> $Options -contains $ID
False

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.