且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PowerShell:-替换,正则表达式和($)美元符号出现问题

更新时间:2023-02-22 13:57:15

您可以尝试以下方法:

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

请注意$$$2.结果为$,内容为$2.

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