2015-07-13 233 views
1

我正在嘗試開發一個腳本,用新的測試字符串替換輸入文本中的某些標記。隨着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

回答

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 
} 

的作品,因爲在正則表達式,你必須逃離$用正則表達式轉義字符\

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

-replace治療的第一個參數作爲正則表達式模式。在正則表達式中,$是一個特殊字符,表示字符串的最後一個字符位置(「結束」)。因此,當試圖在字符串中匹配文字字符$時,您需要將其轉義。

您可以使用[regex]::Escape($pattern)此:

$repl = @{} 
$repl.add([regex]::Escape('$SVN'),"myworkspace\BRANCH71") 
$repl.add([regex]::Escape('$REL'),"72")