ChadJPetersen
ChadJPetersen

Reputation: 393

Powershell Regex capture group not being inserted in replace

I have a string

"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"

that I am trying to escape the spaces in and turn into

"C:\'Program Files (x86)'\'Microsoft Visual Studio 10.0'\Common7\IDE\"

my regex code is

"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\" -replace '(?<=\\)(?<loc>.*?\s+.*?)(?=\\)', "'${loc}'"

but for some reason my outut is

"C:\''\''\Common7\IDE\"

any insight on why this might be happening?

Upvotes: 0

Views: 1253

Answers (1)

ChadJPetersen
ChadJPetersen

Reputation: 393

either

-replace '(?<=\)(?<loc>.*?\s+.*?)(?=\)', '''${loc}'''

or

-replace '(?<=\)(?<loc>.*?\s+.*?)(?=\)', "'$loc'"`

works

The reason '''${loc}''' works is because '' is the escape sequence for ' (not \' like the rest of regex). the reason "'$loc'"` works, is because the $ needs to be escaped so that powershell does not parse it before passing it into the regex engine.

Upvotes: 4

Related Questions