删除除使用正则表达式c#

本文关键字:正则表达式 删除 | 更新日期: 2023-09-27 18:11:31

我想剥离所有的html,但保留<b>标记使用regex。有没有更好的方法来代替

  1. <b>替换为非html标签,如$b$
  2. 删除所有的html标签使用<[^>]*>
  3. 将$b$替换为<b>

删除除<b>使用正则表达式c#

下面的方法只允许打开和关闭b标记。所有其他标签被删除。

var teststring = "Test <b>test</b> lorem <i>ipsum</i>";
var pattern = @"(?!</?b>)<.*?>"; // assuming open and closing tags are retained
Console.WriteLine(Regex.Replace
       (teststring,
         pattern,
         String.Empty,
         RegexOptions.Multiline));
输出:Test <b>test</b> lorem ipsum