删除未使用的(空)HTML标记

时间:2014-10-06 23:13:11

标签: c# regex replace html-agility-pack

我正在寻找清除/删除所有HTML标签的方法......

例如:

<p></p><div> to make links</div><b> </b>
<a href="http://foo.com"></a><p> for linebreak add 2 spaces at end
</p><strong></strong><i></i>

要:

<div> to make links</div><p> for linebreak add 2 spaces at end</p>

//我确定它不是公告。

4 个答案:

答案 0 :(得分:0)

使用此质量检查作为起点(Regular expression to match empty HTML tags that may contain embedded JSTL?),我们有正则表达式<(\w+)(?:\s+\w+="[^"]+(?:"\$[^"]+"[^"]+)?")*>\s*</\1>

然后,这只是将其提供给.NET的Regex引擎:

Regex r = new Regex(@"<(\w+)(?:\s+\w+=""[^""]+(?:""\$[^""]+"[^""]+)?"")*>\s*</\1>");
String output = r.Replace( inputString, String.Empty );

此正则表达式将匹配<foo bar="baz"> </foo>形式的任何文本,其中属性完全是可选的,并且开始和结束标记之间可能只有空格。

答案 1 :(得分:0)

public static string RemoveUnusedTags(this string source)
{
    return Regex.Replace(source, @"<(\w+)\b(?:\s+[\w\-.:]+(?:\s*=\s*(?:""[^""]*""|'[^']*'|[\w\-.:]+))?)*\s*/?>\s*</\1\s*>", string.Empty, RegexOptions.Multiline);
}

答案 2 :(得分:0)

您可以使用这样的正则表达式:

<(\w+)\s*.*?>\s*?</\1>

<强> Working demo

enter image description here

我们的想法是寻找包含空值的标签(包含或不包含属性)。对于您添加的样本输入,输出为:

<div> to make links</div>
<p> for linebreak add 2 spaces at end
</p>

答案 3 :(得分:0)

<[^>]*>\s*<\/[^>]*>

试试这个。这将删除空标签。参见演示。

http://regex101.com/r/hQ1rP0/26