我正在将数千行批处理代码转换为PowerShell。我正在使用正则表达式来帮助完成这个过程。问题是代码的一部分是:
$`$2
更换后,它只显示$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
答案 0 :(得分:8)
您可以尝试这样的事情:
$origString -replace "(IF /I `"%)(.+)(:.+%`"==`")(.+`")(.+)",'if ($$$2 -match "^$4" ) {$5 }'
请注意$$$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
答案 1 :(得分:0)
尝试这样:
$replacedString = $origString -replace "(IF /I `"%)(.+)(:.+%`"==`")(.+`")(.+)","if ( $`$`$2 -match `"^`$4 ) {`$5 }"