使用 C# 正则表达式删除 HTML 标签 [英] Using C# regular expressions to remove HTML tags

查看:37
本文介绍了使用 C# 正则表达式删除 HTML 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 C# 正则表达式替换/删除所有 HTML 标记,包括尖括号?有人可以帮我提供代码吗?

How do I use C# regular expression to replace/remove all HTML tags, including the angle brackets? Can someone please help me with the code?

推荐答案

如前所述,您不应该使用正则表达式来处理 XML 或 HTML 文档.它们在 HTML 和 XML 文档中表现不佳,因为无法以通用方式表达嵌套结构.

As often stated before, you should not use regular expressions to process XML or HTML documents. They do not perform very well with HTML and XML documents, because there is no way to express nested structures in a general way.

您可以使用以下内容.

String result = Regex.Replace(htmlDocument, @"<[^>]*>", String.Empty);

这适用于大多数情况,但在某些情况下(例如包含尖括号的 CDATA),这不会按预期工作.

This will work for most cases, but there will be cases (for example CDATA containing angle brackets) where this will not work as expected.

这篇关于使用 C# 正则表达式删除 HTML 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆