从字符串中删除 HTML 标记,包括 C# 中的 &nbsp

新手上路,请多包涵

如何在 C# 中使用正则表达式删除所有 HTML 标签,包括 &nbsp。我的字符串看起来像

  "<div>hello</div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;</div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div>"

原文由 rampuriyaaa 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

如果您不能使用面向 HTML 解析器的解决方案来过滤掉标签,这里有一个简单的正则表达式。

 string noHTML = Regex.Replace(inputHTML, @"<[^>]+>|&nbsp;", "").Trim();

理想情况下,您应该再次通过一个处理多个空格的正则表达式过滤器

string noHTMLNormalised = Regex.Replace(noHTML, @"\s{2,}", " ");

原文由 Ravi K Thapliyal 发布,翻译遵循 CC BY-SA 3.0 许可协议

我采用了@Ravi Thapliyal 的代码并制定了一个方法:它很简单,可能不会清理所有内容,但到目前为止它正在做我需要它做的事情。

 public static string ScrubHtml(string value) {
    var step1 = Regex.Replace(value, @"<[^>]+>|&nbsp;", "").Trim();
    var step2 = Regex.Replace(step1, @"\s{2,}", " ");
    return step2;
}

原文由 Don Rolling 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题