我正在尝试开发一个脚本,用新的测试字符串替换输入文本中的某些标记。在this的帮助下,我开发了以下内容:
$repl = @{}
$repl.add('SVN',"myworkspace\BRANCH71")
$repl.add('REL',"72")
$string = 'C:\users\rojomoke\filesREL\SVN\blah.txt'
foreach ($h in $repl.getenumerator())
{
write-host "Line: $($h.name): $($h.value)"
$string = $string -replace "$($h.name)","$($h.value)"
write-host $string
}
生成所需的C:\users\rojomoke\files72\myworkspace\BRANCH71\blah.txt
。
然而,当我尝试使用以$
符号开头标记的标记时,这一切都转到sh ^ H ^ Hpieces。如果在上面的示例中我使用了令牌$REL
和$SVN
,则不会进行替换,而$string
仍为C:\users\rojomoke\files$REL\$SVN\blah.txt
。
我认为我正在与正则表达式扩展或其他东西发生冲突,但我看不出如何。是否可以引用美元符号以使其正常工作?
我正在使用Powershell版本3。
答案 0 :(得分:1)
-replace
运算符使用正则表达式匹配。 $
字符在正则表达式中具有特殊含义("字符串结尾"),其他字符也是如此。为避免这种情况,您必须在搜索字符串中转义这些字符:
$srch = [regex]::Escape('$SVN')
$repl = 'myworkspace\BRANCH71'
$string = 'C:\users\rojomoke\filesREL\$SVN\blah.txt'
$string -replace $srch, $repl
但是,如果你使用类似变量的语法,为什么不使用变量?
$repl = @{
'SVN' = 'myworkspace\BRANCH71'
'REL' = '72'
}
$repl.GetEnumerator() | % { New-Variable -Name $_.Name -Value $_.Value }
$string = "C:\users\rojomoke\files$REL\$SVN\blah.txt"
如果您需要在定义嵌套变量之前定义$string
,则可以使用单引号定义字符串并在以后对其进行评估:
$repl = @{
'SVN' = 'myworkspace\BRANCH71'
'REL' = '72'
}
$repl.GetEnumerator() | % { New-Variable -Name $_.Name -Value $_.Value }
$string = 'C:\users\rojomoke\files$REL\$SVN\blah.txt'
$expandedString = $ExecutionContext.InvokeCommand.ExpandString($string)
答案 1 :(得分:1)
-replace
将第一个参数视为正则表达式模式。在正则表达式中,$
是一个特殊字符,表示字符串的最后一个字符位置(“结束”)。因此,在尝试匹配字符串中的文字字符$
时,您需要将其转义。
您可以使用[regex]::Escape($pattern)
:
$repl = @{}
$repl.add([regex]::Escape('$SVN'),"myworkspace\BRANCH71")
$repl.add([regex]::Escape('$REL'),"72")
答案 2 :(得分:1)
$repl = @{}
$repl.add('\$SVN',"myworkspace\BRANCH71")
$repl.add('\$REL',"72")
$string = 'C:\users\rojomoke\files$REL\$SVN\blah.txt'
foreach ($h in $repl.getenumerator()) {
write-host "Line: $($h.name): $($h.value)"
$string = $string -replace "$($h.name)","$($h.value)"
write-host $string
}
因为在正则表达式中你必须使用正则表达式转义字符$
来转义\
。