Skip to main content
 首页 » 编程设计

c#之使用 Regex 或 XmlParser 替换标签中未包含的文本

2024年02月23日15think

我知道使用正则表达式来解析或操作 HTML/XML 是个坏主意,我通常不会这样做。但由于缺乏替代品而考虑。

我需要使用 C# 替换尚未成为标签(最好是具有特定 ID 的 span 标签)一部分的字符串中的文本。

例如,假设我想用替代文本(在我的例子中是另一个跨度)替换以下文本中不在跨度内的所有 ABC 实例

ABC at start of line or ABC here must be replaced but, <span id="__publishingReusableFragment" >ABC inside span must not be replaced with anything. Another ABC here </span> this ABC must also be replaced

我尝试将正则表达式与前瞻和后视断言一起使用。沿线的各种组合

string regexPattern = "(?<!id=\"__publishingReusableFragment\").*?" + stringToMatch + ".*?(?!span)"; 

但放弃了。

我尝试将它加载到 XElement 中并尝试从那里创建一个编写器并获取不在节点内部的文本。但也想不通。

XElement xel = XElement.Parse("<payload>" + inputString + @"</payload>"); 
XmlWriter requiredWriter = xel.CreateWriter(); 

我希望以某种方式使用编写器来获取不属于节点的字符串并替换它们。

基本上,我愿意接受解决此问题的任何建议/解决方案。

在此先感谢您的帮助。

请您参考如下方法:

resultString = Regex.Replace(subjectString,  
    @"(?<!              # assert that we can't match the following  
                        # before the current position:  
                        # An opening span tag with specified id 
     <\s*span\s*id=""__publishingReusableFragment""\s*> 
     (?:                # if it is not followed by... 
      (?!<\s*/\s*span)  # a closing span tag 
      .                 # at any position between the opening tag 
     )*                 # and our text 
    )                   # End of lookbehind assertion 
    ABC                 # Match ABC",  
    "XYZ", RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace); 

将与有关 HTML 解析的所有注意事项一起使用(您似乎知道,所以我不会在这里重复它们)仍然有效。

正则表达式匹配 ABC如果它前面没有空缺 <span id=__publishingReusableFragment">标记,如果没有关闭 <span>两者之间的标签。如果可以嵌套<span>显然会失败标签。