快速移除字串中所有 HTML 標籤(`
///
/// 移除所有 HTML 標籤
///
public static string StripHtml(string html)
{
if (string.IsNullOrEmpty(html)) return html;
// 匹配 <...> 或 ,非貪婪
return Regex.Replace(html, @"?[^>]+>", string.Empty);
}
private static readonly Regex _htmlTagRegex = new Regex(
@"?[^>]+>",
RegexOptions.Compiled | RegexOptions.Singleline);
public static string StripHtmlFast(string html)
{
return string.IsNullOrEmpty(html) ? html : _htmlTagRegex.Replace(html, string.Empty);
}
| 方法 | 耗時 | 相對 |
|---|---|---|
| `Regex.Replace` (實例化每次) | ~1,200 ms | 1.0x |
| 靜態 `Compiled` Regex | ~350 ms | 3.4x 快 |
| `HtmlAgilityPack` 解析 | ~2,800 ms | 0.4x (但語意正確) |
| 場景 | Regex 足夠? | 建議方案 |
|---|---|---|
| 簡單標籤移除、無巢狀結構 | ✅ 是 | 本文 Regex |
| 含 `
Copyright © 程式碼之家 All Rights Reserved
|