Reputation: 31
I am trying to test if a string is in one of two formats: Title (Year) or Title (Year) [Addl]
For the first, this works: if ($name -like "* (*)")...
For the second, this does not work: if ($name -like "* (*) [*]")...
I know the brackets make it think it is a regular expression. How do I make it not a regular expression?
Thanks for your assistance!!!
Upvotes: 2
Views: 69
Reputation: 60683
For Wildcard expressions in PowerShell, the escape character is the backtick `
:
'Title (Year)' -like '* (*)' # => True
'Title (Year) [Addl]' -like '* (*) `[*]' # => True
One way to test this is using [WildcardPattern]::Escape(..)
:
[WildcardPattern]::Escape('[]') # => `[`]
If you want to test the pattern using regular expressions you would be using the -match
operator, and the escape character would be the backslash \
:
'Title (Year)' -match '^\w+\s\(\w+\)$' # => True
'Title (Year) [Addl]' -match '^\w+\s\(\w+\)\s\[\w+]$' # => True
And, as briantist's helpful comment points out, you can use [regex]::Escape(..)
to escape regex special characters:
[regex]::Escape('()[]') # => \(\)\[]
Upvotes: 4