如何在 C# 中编写"Strip HTML Tags"函数



我得到了下面的StripHTMLTags函数代码,它在VBSCript中工作得很好,现在我想用c#编写相同的函数

Function StripHTMLTags(ByVal sHTML)
    Dim objRegExp, sOutput
    sHTML = Replace(Replace(Trim(sHTML & ""), "&lt;", "<"), "&gt;", ">") ' ** PREVENT NULL ERRORS **
    If Len(sHTML) > 0 Then
        Set objRegExp = New RegExp
        With objRegExp
            .IgnoreCase = True
            .Global = True
   .Pattern= "<[^>]+>"
            ' ** REPLACE ALL HTML TAG MATCHES WITH THE EMPTY STRING **
            sOutput = .Replace(sHTML, "")
        End With
        Set objRegExp = Nothing
        StripHTMLTags = sOutput
    Else
        StripHTMLTags = ""
    End If
End Function

您尝试过Regex.Replace吗?

的例子:

    static string stripHTMLTags1(string html)
    {
        string pattern = @"<[^>]+>";
        var expression = new Regex(pattern);
        return expression.Replace(html, String.Empty);
    }
    static string stripHTMLTags2(string html)
    {
        // From http://gskinner.com/RegExr/
        string pattern = @"</?w+((s+w+(s*=s*(?:"".*?""|'.*?'|[^'"">s]+))?)+s*|s*)/?>";
        var expression = new Regex(pattern);
        return expression.Replace(html, String.Empty);
    }

RegExr

下面是从HTML输入中剥离标签的正则表达式:

也可以参阅Stack Overflow的文章,其中详细介绍了如何使用c#剥离HTML标签。

克里斯。