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

不羁的心 提交于 2019-12-01 18:35:07

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

try like this:

 $replacedString = $origString -replace "(IF /I `"%)(.+)(:.+%`"==`")(.+`")(.+)","if ( $`$`$2 -match `"^`$4 ) {`$5 }"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!