提供一個可直接使用的 C# 方法 DealHtml,透過多組 Regex.Replace 移除指定的成對標籤與單標籤,保留文字內容。
public string DealHtml(string str)
{
// 移除 table 相關標籤
str = Regex.Replace(str, @"<(table|tbody|tr|td|th)[^>]*>|</(table|tbody|tr|td|th)>", "", RegexOptions.IgnoreCase);
// 移除 div、blockquote、fieldset、legend
str = Regex.Replace(str, @"<(div|blockquote|fieldset|legend)[^>]*>|</(div|blockquote|fieldset|legend)>", "", RegexOptions.IgnoreCase);
// 移除 br 標籤(含屬性與自閉合)
str = Regex.Replace(str, @"<br[^>]*", "", RegexOptions.IgnoreCase);
str = str.Replace("<br>", "");
// 其餘標籤(img、font、a、span 等)註解保留,視需求啟用
return str;
}
說明:
IgnoreCase 忽略大小寫。<tag[^>]*>|</tag> 同時匹配開啟標籤(含屬性)與關閉標籤。> 等),複雜場景建議使用 HtmlAgilityPack 等解析器。