Tim Lloyd
Tim Lloyd

Reputation: 38474

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 doesn't change the unexpected result, e.g:

> "Debug|x86" -match "Debug`|x128" 
True

Upvotes: 2

Views: 9298

Answers (3)

Michael Sorens
Michael Sorens

Reputation: 36738

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: enter image description here

Upvotes: 1

Shay Levy
Shay Levy

Reputation: 126872

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

Upvotes: 9

Tim Lloyd
Tim Lloyd

Reputation: 38474

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".

Upvotes: 5

Related Questions