PowerShell: -replace, regex and ($) dollar sign woes
Asked Answered
A

2

4

I am in the process of converting thousands of lines of batch code into PowerShell. I'm using regex to help with this process. The problem is part of the code is:

$`$2

When replaced it just shows $2 and doesn't expand out the variable. I've also used single quotes for the second portion of replace instead of escaping the variables, same result.

$origString = @'
IF /I "%OPERATINGSYSTEM:~0,6%"=="WIN864" SET CACHE_OS=WIN864
...many more lines of batch code
'@

$replacedString = $origString -replace "(IF /I `"%)(.+)(:.+%`"==`")(.+`")(.+)","if ( $`$2 -match `"^`$4 ) {`$5 }"

$replacedString
Abducent answered 22/2, 2012 at 19:36 Comment(1)
Just for completeness sake whenever you post a string manipulation question, It would help everyone if you could give an example of the text before the manipulation (which you have) and what the string should look like after the manipulation.Register
W
8

You could try something like this:

$origString -replace "(IF /I `"%)(.+)(:.+%`"==`")(.+`")(.+)",'if ($$$2 -match "^$4" ) {$5 }'

Note the $$$2. This evaluates to $ and content of $2.


Some code to show you the differences. Try it yourself:

'abc' -replace 'a(\w)', '$1'
'abc' -replace 'a(\w)', "$1"  # "$1" is expanded before replace to ''
'abc' -replace 'a(\w)', '$$$1'
'abc' -replace 'a(\w)', "$$$1" #variable $$ and $1 is expanded before regex replace
                               #$$ and $1 don't exist, so they are expanded to ''

$$ = 'xyz'
$1 = '123'
'abc' -replace 'a(\w)', "$$$1`$1" #"$$$1" is expanded to 'xyz123', but `$1 is used in regex
Wailoo answered 22/2, 2012 at 19:48 Comment(2)
I was evaluating and trying to understand your examples and I don't understand why THIS: 'abc' -replace 'a(\w)', '$1' AND THIS: 'abc' -replace 'a(\w)', "$1" is different?Abducent
It's because '$1' and "$1" are (after you hit Enter or run the script) first parsed by PowerShell. The '$1' and "$1" are evaluated to strings according to some rules (see e.g. computerperformance.co.uk/powershell/powershell_quotes.htm and blogs.msdn.com/b/powershell/archive/2006/07/15/… ). And after that the -replace operator is executed. It's how the interpreter works.Wailoo
C
0

try like this:

 $replacedString = $origString -replace "(IF /I `"%)(.+)(:.+%`"==`")(.+`")(.+)","if ( $`$`$2 -match `"^`$4 ) {`$5 }"
Claw answered 22/2, 2012 at 19:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.