2011-10-13 10 views
1

我得到了在其下面的VBScript做工精細StripHTMLTags功能代碼,現在我想同樣的功能將被寫入C#如何寫C#「地帶HTML標籤」功能

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 

請建議,因爲它實在是困惑我。

+1

您是否嘗試過?你有什麼問題? – christofr

+0

我期待有良好的正則表達式,需要html字符串作爲輸入將給出條紋html –

+2

可能的重複[使用C#正則表達式來刪除HTML標記](http://stackoverflow.com/questions/787932/using-c-正則表達式可以拆卸-HTML標籤)。 @christofr,顯然不是搜索。 :) – bzlm

回答

1

您試過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