萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

正則表達式精準刪除指定 HTML 標籤:保留白名單、避免部分匹配陷阱的 C# 實作

爬蟲抓取、使用者輸入、第三方內容嵌入常攜帶雜亂 HTML。需求:**刪除危險/多餘標籤,保留安全白名單 (如 a、img、br、strong、span、b、li)**。單純 `<[^>]+>` 會誤殺白名單,需用**負向前瞻**精準排除。

核心正則邏輯:負向前瞻排除白名單

<(?!(\/?\s?(?:a|img|br|strong|b|span|li)\b))[^>]+>

逐段拆解

片段含義
<匹配標籤起始 `<`
(?! ... )**負向前瞻**:斷言後面**不匹配**括號內模式
\/?\s?可選 `/` (結束標籤) + 可選空白
(?:a|img|br|strong|b|span|li)白名單標籤名,**非捕獲群組**
\b**單字邊界**:防止 `a` 匹配到 `address`、`article`、`aside`
[^>]+匹配非 `>` 字元 (標籤屬性內容)
>匹配標籤結束 `>`

C# 完整實作:動態白名單、編譯優化、大小寫不敏感

using System;
using System.Text.RegularExpressions;

public static class HtmlSanitizer
{
    // 白名單:需保留的標籤名稱 (小寫)
    private static readonly string[] AllowTags = { "a", "img", "br", "strong", "b", "span", "li", "ul", "ol", "p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "code", "pre", "em", "i", "u", "mark" };

    // 編譯一次,全程複用,效能最佳
    private static readonly Regex TagRegex = BuildTagRegex(AllowTags);

    private static Regex BuildTagRegex(string[] tags)
    {
        // 組合:(?:a|img|br|...) 非捕獲群組
        string tagAlternation = string.Join("|", tags);
        // 模式:<(?!(/?\s?(?:tag1|tag2|...)\b))[^>]+>
        string pattern = $@"<(?!(/?\s?(?:{tagAlternation})\b))[^>]+>";
        return new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
    }

    /// 
    /// 移除非白名單 HTML 標籤,保留文字內容
    /// 
    public static string Sanitize(string html)
    {
        if (string.IsNullOrEmpty(html)) return html;
        return TagRegex.Replace(html, string.Empty);
    }

    /// 
    /// 進階:允許呼叫端自訂白名單 (合併預設)
    /// 
    public static string Sanitize(string html, params string[] extraTags)
    {
        if (string.IsNullOrEmpty(html)) return html;
        var merged = AllowTags.Concat(extraTags).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
        var regex = BuildTagRegex(merged);
        return regex.Replace(html, string.Empty);
    }
}

關鍵修正:單字邊界 `\b` 解決部分匹配 Bug

**無 `\b` 時**:白名單含 `a` → `

`、`
`、`
copyright © 萬盛學電腦網 all rights reserved