Chris Reeve
Chris Reeve

Reputation: 328

Matching Variables using Powershell Match

I need to parse some config files and find a match. I've simplified the problem to this. Why doesn't powershell match the backslash even when it's been escaped? It works if I remove the backspace from the code below.

Find $b in $a:

$a="lorum [\test] ipsum"
$b="[\test]" 

([regex]::Escape($a )) -match ([regex]::Escape($b))

Upvotes: 2

Views: 2395

Answers (1)

Frode F.
Frode F.

Reputation: 54821

It's because you're escaping the string itself. The part before -match should be a normal string, while the part after needs to be a regex pattern. What your command actually does is comparing these strings(think of them as normal strings):

"lorum \[\\test\] ipsum" contains "[\test]"

Which is never true. Try matching the string $a to the escaped pattern $b:

$a="lorum [\test] ipsum"
$b="[\test]" 

$a -match ([regex]::Escape($b))

Upvotes: 5

Related Questions