PowerShell:-替换,正则表达式和($)美元符号出现问题 [英] PowerShell: -replace, regex and ($) dollar sign woes
本文介绍了PowerShell:-替换,正则表达式和($)美元符号出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将数千行批处理代码转换为PowerShell.我正在使用正则表达式来帮助完成此过程.问题是代码的一部分是:
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
替换后,它仅显示$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
推荐答案
您可以尝试以下方法:
$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
这篇关于PowerShell:-替换,正则表达式和($)美元符号出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文