我正在尝试编写PowerShell脚本来替换我放入XML文件中的标记的内容。这些标记在XML中多次出现,这导致第一个标记与最后一个标记之间的所有内容都被替换,因为它不会在第一次找到结束标记时停止。
我正在使用这个:
$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)
,但也可以。我应该做什么才能使它起作用的任何想法。
谢谢,
理查德
最佳答案
您应该使用*
的非贪婪版本,即*?
。有关更多信息,请参见: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;
关于regex - PowerShell-使用REGEX替换每个标签的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7993663/