c# - 用于删除 XML 标记及其内容的正则表达式

标签 c# .net xml vb.net regex

我有以下字符串,我想删除 <bpt *>*</bpt><ept *>*</ept> (注意其中也需要删除的附加标记内容)不使用 XML 解析器(对于小字符串来说开销太大)。

The big <bpt i="1" x="1" type="bold"><b></bpt>black<ept i="1"></b></ept> <bpt i="2" x="2" type="ulined"><u></bpt>cat<ept i="2"></u></ept> sleeps.

VB.NET 或 C# 中的任何正则表达式都可以。

最佳答案

如果您只想从字符串中删除所有标签,请使用此 (C#):

try {
    yourstring = Regex.Replace(yourstring, "(<[be]pt[^>]+>.+?</[be]pt>)", "");
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

编辑:

我决定在我的解决方案中添加一个更好的选择。如果有嵌入的标签,前面的选项将不起作用。这个新的解决方案应该去除所有 <**pt*> 标签,嵌入与否。此外,此解决方案使用对原始 [be] 匹配项的反向引用,以便找到完全匹配的结束标记。该解决方案还创建了一个可重用的 Regex 对象以提高性能,以便每次迭代都不必重新编译 Regex:

bool FoundMatch = false;

try {
    Regex regex = new Regex(@"<([be])pt[^>]+>.+?</\1pt>");
    while(regex.IsMatch(yourstring) ) {
        yourstring = regex.Replace(yourstring, "");
    }
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

附加说明:

在评论中,一位用户表达了对“.”的担忧。模式匹配器将是 CPU 密集型的。虽然在独立的贪婪“.”的情况下这是真的,但使用非贪婪字符“?”导致正则表达式引擎只向前看,直到它找到模式中下一个字符的第一个匹配项与贪婪的“。”这需要引擎一直向前看直到字符串的末尾。我用 RegexBuddy作为正则表达式开发工具,它包含一个调试器,可让您查看不同正则表达式模式的相对性能。如果需要,它还会自动注释您的正则表达式,因此我决定在此处包含这些注释以解释上面使用的正则表达式:

    // <([be])pt[^>]+>.+?</\1pt>
// 
// Match the character "<" literally «<»
// Match the regular expression below and capture its match into backreference number 1 «([be])»
//    Match a single character present in the list "be" «[be]»
// Match the characters "pt" literally «pt»
// Match any character that is not a ">" «[^>]+»
//    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
// Match the character ">" literally «>»
// Match any single character that is not a line break character «.+?»
//    Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
// Match the characters "</" literally «</»
// Match the same text as most recently matched by backreference number 1 «\1»
// Match the characters "pt>" literally «pt>»

关于c# - 用于删除 XML 标记及其内容的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/121656/

相关文章:

c# - 具有整数键的哈希表(字典等)

.net - 关于将应用程序从 .Net Framework 移植到 .Net core 的问题

c# - 有没有像样的 ADO.NET Helper 实用程序?

c# - 对 WCF 调用进行单元测试,是否可能以及如何进行?

sql - 在 SQL 中使用 FOR XML 为同一属性选择多个值

c# - session 过早退出

c# - 如何修复 .NET Windows 应用程序在启动时崩溃并出现异常代码 : 0xE0434352?

c# - 添加引用asp.net后编译错误

xml - Grails ApplicationContext.xml grailsResourceLoader

php - 为什么当我将 XML 发送到 PHP 时,节点是小写的,但当我在 PHP 中解析它们时,它们是大写的?