【问题标题】:RegEx replace for invalid Numeric character reference正则表达式替换无效的数字字符引用
【发布时间】:2016-01-08 12:35:29
【问题描述】:

在替换 Xml 文档中的无效数字字符引用时需要一些正则表达式帮助。

由于XmlWriter 中的一个已知错误,我们在生产中使用的一些 Xml 数据变得不可读,在该错误中,当您编写 XML 实体时分号会被丢弃。不幸的是,由于某种奇怪的原因,生产环境没有在最新的 .Net 框架上运行,这导致大量此类数据被插入到数据库中,现在我必须找到一个修复程序来读取和修复这些数据不知何故。

一个误解的 XML 示例(在下面的 XML 中查找 ฝ&Σ):

<TestInvalidUnicodeReading Desc="a&#xF1;o &#x20AC;  &#x3A3 &#xC6; Jako efektivn&#x11;B;j&#x161;&#xED; se n&#xE1;m jev&#xED; po&#x159&#xE1d&#xE1;n&#xED; tzv. st&#x159ed;nictv&#xED;m na&#x161;ich an&#xFDc;h dealer&#x16F; v &#x10Cec;h&#xE1c;h a na Morav&#x11;B, kter&#xE9; prob&#x11;Bhnou v pr&#x16Fb;&#x11;Bhu z&#xE1;&#x159;&#xED; a &#x159;&#xEDjna.bddb26e234c5452aab7720c581e137f7" />

现在为了解决这个问题,我设计了以下 RegEx solution 并在 C# 中使用它来查找匹配项并添加缺少的分号,这部分工作:

&((?:#([0-9]+)|#x([0-9a-fA-F]+)|([0-9a-zA-Z]+))[?&0-9a-zA-Z ])

现在问题出在 ฝ& 部分。

因为当上面的 RegEx 匹配上一个匹配时,下一个 ฝ& 将被跳过。有人可以帮我解决这个 RegEx 问题吗?

【问题讨论】:

    标签: c# regex xml


    【解决方案1】:

    我认为您可以使用negative lookahead assertion 改进正则表达式:

    &(#[0-9]+(?![0-9;])|#x[0-9a-fA-F]+(?![0-9a-fA-F;]))
    

    只会匹配后面没有; 的数字字符引用。

    说明:

    &                 # Match &
    (                 # Start of capturing group:
     #[0-9]+          # Match either # plus digits  
     (?![0-9;])       # as long as they are not followed by a semicolon or more digits
    |                 #
     #x[0-9a-fA-F]+   # match #x plus hex digits
     (?![0-9a-fA-F;]) # as long as they are not followed by semicolon or hex
    )                 # End of group
    

    测试它live on regex101.com

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 2013-02-19
      • 2015-11-30
      • 2011-02-03
      相关资源
      最近更新 更多