use*_*442 1 regex powershell replace
我正在尝试编写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;
Run Code Online (Sandbox Code Playgroud)
该文件包含以下内容:
<!--MyCustom-StartTag-->
Lots of content
<!--MyCustom-EndTag-->
More stuff here
<!--MyCustom-StartTag-->
Lots of content
<!--MyCustom-EndTag-->
Run Code Online (Sandbox Code Playgroud)
我最终得到:
<!--MyCustom-StartTag-->
New Content Here
<!--MyCustom-EndTag-->
Run Code Online (Sandbox Code Playgroud)
代替:
<!--MyCustom-StartTag-->
New content
<!--MyCustom-EndTag-->
More stuff here
<!--MyCustom-StartTag-->
New content
<!--MyCustom-EndTag-->
Run Code Online (Sandbox Code Playgroud)
我尝试过使用:(?!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;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2396 次 |
最近记录: |