从字符串中去除HTML标签

7

我正在编写一个程序,它应该从字符串中删除HTML标签。我一直在尝试替换所有以"<"开头且以">"结尾的字符串。但是(显然因为我在这里询问),这一直没有成功。以下是我尝试过的方法:

StrippedContent = Regex.Replace(StrippedContent, "\<.*\>", "")

这只返回原始字符串中似乎是随机的一部分。我也尝试过

For Each StringMatch As Match In Regex.Matches(StrippedContent, "\<.*\>")
    StrippedContent = StrippedContent.Replace(StringMatch.Value, "")
Next

有一个方法(返回似乎是原始字符串的随机部分),但是它与之前的方法相同。有没有更好的方法?更好的意思是能够正常工作的方法。


我已经编辑了你的标题。请参考“问题的标题应该包含“标签”吗?”,在那里达成共识是“不应该”。 - John Saunders
3个回答

32

描述

此表达式将:

  • 查找并替换所有标签为空
  • 避免问题边缘情况

正则表达式:<(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*>

替换为:nothing

enter image description here

例子

示例文本

请注意在鼠标悬停功能中的复杂边缘情况

these are <a onmouseover=' href="NotYourHref" ; if (6/a>3) { funRotator(href) } ; ' href=abc.aspx?filter=3&prefix=&num=11&suffix=>the droids</a> you are looking for.

代码

Imports System.Text.RegularExpressions
Module Module1
  Sub Main()
    Dim sourcestring as String = "replace with your source string"
    Dim replacementstring as String = ""
    Dim matchpattern as String = "<(?:[^>=]|='[^']*'|=""[^""]*""|=[^'""][^\s>]*)*>"
    Console.Writeline(regex.Replace(sourcestring,matchpattern,replacementstring,RegexOptions.IgnoreCase OR RegexOptions.IgnorePatternWhitespace OR RegexOptions.Multiline OR RegexOptions.Singleline))
  End Sub
End Module

替换后的字符串

these are the droids you are looking for.

3
到目前为止,这是我见过的最好的与这个主题相关的正则表达式!+1 - Sebastian
1
使用这个答案,如何尝试避免 <br> 标签,以便换行符出现?我有一个包含许多换行符的文档,因此当使用上述答案时,文本会返回为一个大段落。 - Nicholas Aysen
1
@NicholasAysen 我猜你想替换除了<br>标签之外的所有HTML标签?如果是这样,那么你只需要添加一个负向前瞻,如<(?!br)(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*> 也可以参考这个链接,干杯。 - Ro Yo Mi
@Denomales 非常感谢。我还发现,在进一步查看我提取的数据时,有一些标签是双<<和>>。所以我只是用单个标签替换了所有这些标签,并且不需要改变其他任何内容。但我肯定会记住这个方法,以备将来使用。谢谢。 - Nicholas Aysen
这里对输入做了一些假设。至少:标签内不应有换行符,属性名和属性值之间的=周围不应有空格(例如,<p id = ">">会失败)。 - Mitar
注意:它会剥离<style>标签,但不会剥离其内容。 - Lazar

4

这证明了你应该总是在Google上寻找答案。这里有一个方法,我从http://www.dotnetperls.com/remove-html-tags-vbnet得到的。

Imports System.Text.RegularExpressions

Module Module1
    Sub Main()
        Dim html As String = "<p>There was a <b>.NET</b> programmer " +
          "and he stripped the <i>HTML</i> tags.</p>"
        Dim tagless As String = StripTags(html)
        Console.WriteLine(tagless)
    End Sub
    Function StripTags(ByVal html As String) As String
        Return Regex.Replace(html, "<.*?>", "")
    End Function
End Module

如果您的标记包含类似于:some text<a onmouseover="if ( 6 > x ) { funDoSomething ; } ">more text这样的属性,则此解决方案将存在问题。 - Ro Yo Mi

1
这是一个使用 Ro Yo Mi 发布的正则表达式模式的简单函数。
<Extension()> Public Function RemoveHtmlTags(value As String) As String
    Return Regex.Replace(value, "<(?:[^>=]|='[^']*'|=""[^""]*""|=[^'""][^\s>]*)*>", "")
End Function

演示:
Dim html As String = "This <i>is</i> just a <b>demo</b>.".RemoveHtmlTags()
Console.WriteLine(html)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接