正则表达式将替换字符串以外的所有内容

时间:2018-12-03 01:19:52

标签: c# regex

我正在使用正则表达式替换使用以下表达式的span标记内的所有格式,并且有效。

retValue = System.Text.RegularExpressions.Regex.Replace(retValue, @"<span[^>]*>", "<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>");

1 个答案:

答案 0 :(得分:-2)

您需要正确转义特殊字符:

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