简体   繁体   English

删除HTML标记,但不使用正则表达式C#

[英]Strip html tags except <b> using regex c#

I wanted to strip all the html but preserve <b> tags using regex. 我想剥离所有html,但使用正则表达式保留<b>标记。 Is there a better way to do instead of 有没有更好的方法可以代替

  1. Replace <b> with a non html tag like $b$ <b>替换为非html标签,例如$ b $
  2. Remove all html tags using <[^>]*> 使用<[^>]*>删除所有html标记
  3. Replace $b$ with <b> 将$ b $替换为<b>

Below is one approach that will only permit opening and closing b tags. 以下是一种仅允许打开和关闭b标签的方法。 Any other tags are removed. 任何其他标签都将被删除。

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));

Outputs: Test <b>test</b> lorem ipsum 输出: Test <b>test</b> lorem ipsum

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM