'PowerShell -like formatting
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!!!
Solution 1:[1]
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('()[]') # => \(\)\[]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |