【问题标题】:Powershell Regex to replace XML tag valuesPowershell Regex 替换 XML 标记值
【发布时间】:2013-05-04 14:47:15
【问题描述】:

我正在尝试使用 Powershell 从文件中解析以下 XML,但实际上没有使用 [xml] 将其加载为 XML 文档,因为该文档包含错误。

<data>
  <company>Walter & Cooper</company>
  <contact_name>Patrick O'Brian</contact_name>
</data>

要成功加载文档,我需要通过替换特殊字符来修复错误,如下所示

& with &amp;
< with &lt;
' with &apos; etc..

我知道我可以做这样的事情来查找和替换文档中的字符

(Get-Content $fileName) | Foreach-Object {
  $_-replace '&', '&amp;' `
    -replace "'", "&apos;" `
    -replace '"', '&quot;'} | Set-Content $fileName

但这将替换文件中所有位置的字符,我只对检查 等 xml 标签内的字符并用 xml 安全实体替换它们感兴趣,以便生成的文本是一个有效的文档,我可以使用 [ xml]。

【问题讨论】:

    标签: xml regex powershell


    【解决方案1】:

    一点点正则表达式后视和前瞻应该可以解决问题:

    $str = @'
    <data>
      <company>Walter & Cooper & Brannigan</company>
      <contact_name>Patrick & O'Brian</contact_name>
    </data>
    '@
    
    $str -replace '(?is)(?<=<company>.*?)&(?=.*?</company>)', '&amp;'
    

    【讨论】:

      【解决方案2】:

      这样的东西应该适用于您需要替换的每个字符:

      $_-replace '(?<=\W)(&)(?=.*<\/.*>)', '&amp' `
        -replace '(?<=\W)(')(?=.*<\/.*>)', '&apos;' `
        -replace '(?<=\W)(")(?=.*<\/.*>)', '&quot;' `
        -replace '(?<=\W)(>)(?=.*<\/.*>)', '&gt;' `
        -replace '(?<=\W)(\*)(?=.*<\/.*>)', '&lowast;' } | Set-Content $fileName
      

      它对非单词字符进行正向回溯,然后是捕获组,然后是正向预读。

      例子:

      更新:http://regex101.com/r/aY8iV3 | 原文:http://regex101.com/r/yO7wB1

      【讨论】:

      • 谢谢,这很好用,但在 符号出现在 >失败测试用例 &*>"
      • @Raj - 对于符号&lt; &gt;,您可以使用非单词字符\W 进行积极的后视,然后以积极的前瞻继续捕获组。我已经更新了答案/示例。
      猜你喜欢
      • 2011-01-07
      • 2013-11-19
      • 2023-03-28
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2011-12-21
      相关资源
      最近更新 更多