4
我有一個形式爲-content-
的字符串,我想用&content&
替換它。我如何在PowerShell中進行替換?在PowerShell中替換子串
我有一個形式爲-content-
的字符串,我想用&content&
替換它。我如何在PowerShell中進行替換?在PowerShell中替換子串
內置-replace
運營商允許你使用正則表達式這個如:
C:\PS> '-content-' -replace '-([^-]+)-', '&$1&'
&content&
請注意,對替換字符串使用單引號是必不可少的,所以PowerShell不會解釋$ 1捕獲組。
PowerShell的字符串是隻是.NET字符串,因此您可以:
PS> $x = '-foo-'
PS> $x.Replace('-', '&')
&foo&
...或:
PS> $x = '-foo-'
PS> $x.Replace('-foo-', '&bar&')
&bar&
很顯然,如果你想保留的結果,將其分配給另一個變量:
PS> $y = $x.Replace($search, $replace)
但此解決方案也符合-content並將其替換爲&content。 – 2013-02-16 17:38:25