【问题标题】:Regular Expression replace everything except a string正则表达式替换除字符串之外的所有内容
【发布时间】:2018-12-03 01:19:51
【问题描述】:

我正在使用正则表达式来使用以下表达式替换 span 标签中的任何格式,并且它有效。

retValue = System.Text.RegularExpressions.Regex.Replace(retValue, @"<span[^>]*>", "<span>");

现在,我想替换除“下划线”之外的跨度标记中的任何格式。例如在下面的字符串中,我想删除第二个 span 标签中的格式,但保留第一个 span 标签的格式。

 string retValue = "<p><span style=\"text-decoration: underline;\">Test Underline</span></P><p><span style="color:blue">blue</span></p>";

所以我的 retValue 应该是:

retValue = "<p><span style=\"text-decoration: underline;\">Test Underline</span></P><p><span>blue</span></p>";

我尝试使用以下表达式,但它根本没有替换任何内容。我试图了解这段代码有什么问题以及如何达到预期的结果。

retValue = System.Text.RegularExpressions.Regex.Replace(retValue, @"<span[^style=\""text-decoration:underline;>]*>", "<span>");

【问题讨论】:

  • 您能否做出任何坚定而可靠的保证,以确保样式属性的内容与您的问题中显示的内容没有什么不同?样式属性可以有任意数量的变体,具有任意顺序的不同 CSS 属性(text-decoration 只是其中之一)。然后text-decoration 本身不仅可以有一个underline 值,还可以有一个组合值,例如text-decoration: red underline。除非你能保证 style 属性永远不会有变化的内容,否则:stackoverflow.com/a/1732454/2819245
  • 您可能需要考虑使用 html 解析器而不是正则表达式来处理此问题。

标签: c# regex


【解决方案1】:

需要正确转义特殊字符:

var pattern = "\\<span[^style\\=\\\"text\\-decoration\\:underline\\;\\>]*>";
retValue = System.Text.RegularExpressions.Regex.Replace(retValue, pattern, "<span>");

【讨论】:

  • 这不是在回答问题,它根本不是一个有意义的正则表达式模式。请查阅关于正则表达式的教程,特别是关于[][]^的功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-01
  • 2016-12-20
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多