2011-11-03 33 views
1

我正在嘗試編寫一個PowerShell腳本來替換已放入XML文件的標記的內容。標籤在XML中出現多次,這導致第一個和最後一個標籤之間的所有內容都被替換,因爲它在第一次找到結束標籤時不會停止。PowerShell - 使用REGEX替換每個標記的內容

我使用這個:

$NewFile = (Get-Content .\myXML_file.xml) -join "" | foreach{$_ -replace "<!--MyCustom-StartTag-->(.*)<!--MyCustom-EndTag-->","<!--MyCustom-StartTag-->New Contents of Tag<!--MyCustom-EndTag-->"}; 
Set-Content .\newXMLfile.xml $newfile; 

該文件具有類似內容:

<!--MyCustom-StartTag--> 
Lots of content 
<!--MyCustom-EndTag--> 
More stuff here 
<!--MyCustom-StartTag--> 
Lots of content  
<!--MyCustom-EndTag--> 

但我是結束了:

<!--MyCustom-StartTag--> 
New Content Here  
<!--MyCustom-EndTag--> 

相反的:

<!--MyCustom-StartTag--> 
New content 
<!--MyCustom-EndTag--> 
More stuff here 
<!--MyCustom-StartTag--> 
New content  
<!--MyCustom-EndTag--> 

我嘗試過使用:(?!MyCustom-StartTag),但它也可以。

任何想法,我應該做些什麼來得到這個工作。

感謝, 理查德

回答

5

您應該使用的*的非貪婪版本,即*?。有關更多信息,請參閱:http://www.dijksterhuis.org/csharp-regular-expression-operator-cheat-sheet/(Powershell使用與C#相同的正則表達式引擎)。

$NewFile = (Get-Content .\myXML_file.xml) -join "" | foreach{$_ -replace "<!--MyCustom-StartTag-->(.*?)<!--MyCustom-EndTag-->","<!--MyCustom-StartTag-->New Contents of Tag<!--MyCustom-EndTag-->"}; 
Set-Content .\newXMLfile.xml $newfile; 
+0

這只是我想要的,謝謝 – user1027442

+0

可愛。在之前我還沒有在.NET regex中使用貪婪/非貪婪的操作符,但我想這是時候記住Perl「駱駝」書提供的常規知識(特別是與正則表達式有關):) –

0

我認爲你剩下的只有一對開始和結束標記的原因是因爲你的查詢模式在搜索字符串中發現的三場比賽。

  1. 第一對開始和結束。

  2. 第二對開始和結束。

  3. 從第一個開始,第二個結束標記(如果最後找到了這個匹配,它實際上將用新值替換第一個和最後一個之間的全部)。

所以在你的「(*)」中,你可能不得不排除任何其他的開始和結束標籤?