2012-02-22 98 views
4

我正在将成千上万行的批处理代码转换为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 
+2

只是为了完整性起见,只要您发布字符串处理的问题,这将有助于每个人,如果你能在操作前给文字的例子(你有哪些)**和**在操作后字符串应该是什么样子。 – EBGreen 2012-02-22 19:44:47

+0

好主意。下次会做。谢谢。 – Vippy 2012-02-22 22:21:29

回答

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 
+0

非常感谢。我也喜欢你给的例子! – Vippy 2012-02-22 20:45:02

+1

我正在评估并试图理解你的例子,我不明白为什么这个:'abc'-replace'a(\ w)','$ 1'和这个:'abc'-replace'a(\ w)' ,“$ 1”是不同的? – Vippy 2012-02-22 21:30:49

+0

这是因为PowerShell首先分析了“$ 1”和“”$ 1“(在您按Enter或运行脚本后)。根据一些规则,“$ 1”和“$ 1”被评估为字符串(参见例如http://www.computerperformance.co.uk/powershell/powershell_quotes.htm和http://blogs.msdn.com /b/powershell/archive/2006/07/15/variable-expansion-in-strings-and-herestrings.aspx)。之后执行'-replace'运算符。这就是口译员的工作方式。 – stej 2012-02-23 06:54:41

0

尝试这样的:

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