Vip*_*ppy 4 regex powershell replace dollar-sign
我正在将数千行批处理代码转换为PowerShell.我正在使用正则表达式来帮助完成这个过程.问题是代码的一部分是:
$`$2
Run Code Online (Sandbox Code Playgroud)
更换时,它只显示$2并不扩展变量.我还使用单引号替换第二部分而不是转义变量,结果相同.
$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
Run Code Online (Sandbox Code Playgroud)
你可以尝试这样的事情:
$origString -replace "(IF /I `"%)(.+)(:.+%`"==`")(.+`")(.+)",'if ($$$2 -match "^$4" ) {$5 }'
Run Code Online (Sandbox Code Playgroud)
请注意$$$2.这评估$和内容$2.
一些代码向您展示差异.亲自尝试一下:
'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
Run Code Online (Sandbox Code Playgroud)