regex - PowerShell-使用REGEX替换每个标签的内容

标签 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;

该文件的内容如下:
<!--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/

相关文章:

php - 如何使用PHP或regex提取图像名称?

powershell - 使用 powershell 更新 SSL 配置

Powershell move 项目访问被拒绝

python - 生成正则表达式列表以替换数据框中的单词列表python

regex - 为什么前瞻和后瞻正则表达式在 Kotlin 中不起作用?

Javascript 正则表达式格式化程序现在允许具有 , 和 的数字。同时

c# - 正则表达式模式不显示匹配项

powershell - Net.WebClient.DownloadFile从批处理文件下载Google云端硬盘文件无法识别某些字符

mysql - 如何在 MySQL 中替换包含反斜杠的字符串

linux - 在 Linux 中替换