开发者

PowerShell String Matching and the Pipe Character

开发者 https://www.devze.com 2023-03-29 09:15 出处:网络
I am having difficulty matching strings in PowerShell that contain the pipe characters. Match returns true in the following scenario when it shouldn\'t:

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:

PowerShell String Matching and the Pipe Character

0

精彩评论

暂无评论...
验证码 换一张
取 消