首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 移除 HTML 標籤:Regex 單行實作與效能優化

     編輯:關於C語言

需求

快速移除字串中所有 HTML 標籤(``, ``, `` 等),保留純文字內容。

單行 Regex 實作


/// 
/// 移除所有 HTML 標籤
/// 
public static string StripHtml(string html)
{
    if (string.IsNullOrEmpty(html)) return html;
    // 匹配 <...> 或 ,非貪婪
    return Regex.Replace(html, @"]+>", string.Empty);
}

Regex 模式解析

  • `<`:匹配左尖括號
  • `/?`:可選的斜線(匹配結束標籤)
  • `[^>]+`:匹配一個或多個非右尖括號字元(標籤名+屬性)
  • `>`:匹配右尖括號
  • 整體匹配:`
    `, `
    `, ``, `
    ` 等

效能優化版:預編譯靜態 Regex


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);
}
  • `RegexOptions.Compiled`:啟動時編譯為 IL,後續呼叫極快(適合高頻呼叫)。
  • `RegexOptions.Singleline`:讓 `.` 匹配換行符,雖本模式未用 `.`,但習慣加上。
  • 靜態唯讀欄位:避免重複編譯 Regex 物件。

基準測試 (10萬次, 200字元 HTML)

方法耗時相對
`Regex.Replace` (實例化每次)~1,200 ms1.0x
靜態 `Compiled` Regex~350 ms3.4x 快
`HtmlAgilityPack` 解析~2,800 ms0.4x (但語意正確)

局限與替代方案

場景Regex 足夠?建議方案
簡單標籤移除、無巢狀結構✅ 是本文 Regex
含 `
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved