PowerShell String Matching and the Pipe Character
I am having difficulty matching strings in PowerShell that contain the pipe characters. Match returns true in the following scenario when it shouldn't:
> "Debug|x86" -match "Debug|x128"
True
I have tried escaping the match argument pipe character, but this doe开发者_运维技巧sn't change the unexpected result, e.g:
> "Debug|x86" -match "Debug`|x128"
True
If you're not sure which characters you need to escape, let the Escape method do the work for you:
PS > [regex]::escape("Debug|x128")
Debug\|x128
It's a regular expression so needs to be escaped with backslash, not PowerShell's backtick, e.g.:
> "Debug|x86" -match "Debug\|x128"
False
As it is a regular expression, If the pipe character is not escaped, it evaluates to "Debug or x128".
Both Chibacity and Shay have revealed the proper way to escape the meta-character in your regular expression. But if you want to understand more about the -match operator and other string comparison operators, you may find this article helpful: Harnessing PowerShell's String Comparison and List-Filtering Features. It comes complete with a one-page wallchart enumerating the various operators in both scalar and array context. Here's a preview:
精彩评论