Regex 版(簡易、效能較好、但不完美)
public static string NoHTML(string htmlString)
{
if (string.IsNullOrEmpty(htmlString)) return string.Empty;
// 1. 移除 script 標籤及內容
htmlString = Regex.Replace(htmlString, @"<script[^>]*>.*?</script>", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
// 2. 移除 style 標籤及內容
htmlString = Regex.Replace(htmlString, @"<style[^>]*>.*?</style>", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
// 3. 移除所有 HTML 標籤
htmlString = Regex.Replace(htmlString, @"<[^>]+>", "", RegexOptions.IgnoreCase);
// 4. 移除多餘空白行與 HTML 註解殘留
htmlString = Regex.Replace(htmlString, @"(\r\n|\n)\s+", "\n", RegexOptions.IgnoreCase);
htmlString = Regex.Replace(htmlString, @"-->", "", RegexOptions.IgnoreCase);
htmlString = Regex.Replace(htmlString, @" ", " ", RegexOptions.IgnoreCase);
return htmlString.Trim();
}
⚠️ Regex 版局限
- 無法正確處理巢狀標籤、屬性值含
>、CDATA、條件式註解
- 異常 HTML(未閉合標籤)可能導致過度/不足移除
- 不處理實體解碼(
< 仍為原文)
專業級方案:HtmlAgilityPack(強烈推薦)
// NuGet: Install-Package HtmlAgilityPack
using HtmlAgilityPack;
public static string StripHtml(string html)
{
if (string.IsNullOrEmpty(html)) return string.Empty;
var doc = new HtmlDocument();
doc.LoadHtml(html);
// 移除 script/style
foreach (var node in doc.DocumentNode.SelectNodes("//script | //style") ?? Enumerable.Empty<HtmlNode>())
node.Remove();
// 取得純文字(自動解碼實體、保留換行)
return doc.DocumentNode.InnerText.Trim();
}
比較表
| 維度 | Regex | HtmlAgilityPack |
| 正確性 | 低(邊界情況易錯) | 高(真實 DOM 解析) |
| 效能 | 高(單純字串操作) | 中(建構 DOM 樹) |
| 實體解碼 | 需自行處理 | 自動 |
| 巢狀/異常 HTML | 不支援 | 容錯處理 |
| 依賴 | 無 | NuGet 套件 |
適用場景建議
- Regex:簡單清理、效能極度敏感、輸入格式可控
- HtmlAgilityPack:使用者輸入內容、CMS 儲存、郵件模板處理、SEO 關鍵字提取、任何生產環境
copyright ©
萬盛學電腦網 all rights reserved