2010-04-09 89 views
3

如何從C#中的字符串中刪除從'<''並以'>'結尾的所有內容。我知道這可以用正則表達式完成,但我不是很好。從C#中的字符串中刪除HTML標籤和評論?

+1

使用HTML解析器像HTML敏捷性包。正則表達式通常是html的糟糕選擇。 – 2010-04-09 19:25:46

+0

在這種情況下,你可以,因爲它是正則表達式的簡單用例。它不同於爲不同標籤解析整個DOM – AuthorProxy 2016-04-11 10:40:09

回答

4

我很快寫了一個最近的小項目的標籤模式就是這個。

string tagPattern = @"<[!--\W*?]*?[/]*?\w+.*?>"; 

我用它像這樣

MatchCollection matches = Regex.Matches(input, tagPattern); 
foreach (Match match in matches) 
{ 
    input = input.Replace(match.Value, string.Empty); 
} 

它可能會需要進行修改,以正確處理腳本或風格的標記。

+0

像魅力一樣工作 – 2010-04-10 20:24:35

+1

'[! - \ W *?]'表示「匹配'!'和'-'範圍內的一個字符,一個非單詞字符,'*'或者'?'「。由於該組是可選的,所以它並沒有受到傷害,但它並不能達到負面預測(這將是'(!! - )','\ W *?'和後面的' *?'根本沒有任何意義)。 – 2010-05-18 13:58:40

1

非正則表達式選項:但它仍然不會解析嵌套標記!

public static string StripHTML(string line) 
     { 
      int finished = 0; 
      int beginStrip; 
      int endStrip; 

      finished = line.IndexOf('<'); 
      while (finished != -1) 
      { 
       beginStrip = line.IndexOf('<'); 
       endStrip = line.IndexOf('>', beginStrip + 1); 
       line = line.Remove(beginStrip, (endStrip + 1) - beginStrip); 
       finished = line.IndexOf('<'); 
      } 

      return line; 
     } 
1

另一個非正則表達式的代碼,工作比8倍速度的正則表達式:

public static string StripTagsCharArray(string source) 
{ 
    char[] array = new char[source.Length]; 
    int arrayIndex = 0; 
    bool inside = false; 
    for (int i = 0; i < source.Length; i++) 
    { 
     char let = source[i]; 
     if (let == '<') 
     { 
      inside = true; 
      continue; 
     } 
     if (let == '>') 
     { 
      inside = false; 
      continue; 
     } 
     if (!inside) 
     { 
      array[arrayIndex] = let; 
      arrayIndex++; 
     } 
    } 
    return new string(array, 0, arrayIndex); 
}