首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C# 移除 HTML 標簽但保留換行樣式:基於 Regex 的精準過濾方案

     編輯:程式設計疑難解答

需求場景

將富文本 HTML 字符串「去標簽化」為純文本,但保留 <br> 換行標簽(或轉換為環境換行符),其他標簽(如 <div>、<b>、<style> 等)全部移除。

核心解決方案:Regex 替換回調

using System.Text.RegularExpressions;

public static string RemoveHtmlKeepBr(string html) {
    if (string.IsNullOrEmpty(html)) return html;

    // 匹配所有標簽: 或 
    // 回調中判斷:若為 br 標簽(不區分大小寫),保留 
;否則移除 string result = Regex.Replace(html, @"</?([a-z\d]+)[^>]*>", m => { string tagName = m.Groups[1].Value.ToLower(); return tagName == "br" ? "<br>" : ""; }, RegexOptions.IgnoreCase); return result; }

代碼解析

組件說明
正則 </?([a-z\d]+)[^>]*>匹配開始標簽 <tag ...> 和結束標簽 </tag>,捕獲組 1 為標簽名(字母數字)。
RegexOptions.IgnoreCase忽略大小寫,兼容 <BR>、<Br> 等寫法。
MatchEvaluator 回調動態決定替換內容:br 保留 <br>,其餘替換為空字符串。

測試驗證

string input = "<div>a<br>b<b style='color:red'>c</b></div>";
string output = RemoveHtmlKeepBr(input);
Console.WriteLine(output); // 輸出: a<br>bc
// 若需在控制台顯示真正換行,可進一步 .Replace("<br>", Environment.NewLine)

進階擴展:保留多個允許標簽

private static readonly HashSet AllowedTags = new HashSet { "br", "p", "hr" };

public static string RemoveHtmlCustom(string html) {
    return Regex.Replace(html, @"</?([a-z\d]+)[^>]*>", m => {
        string tag = m.Groups[1].Value.ToLower();
        return AllowedTags.Contains(tag) ? m.Value : ""; // 保留原標簽完整寫法
    }, RegexOptions.IgnoreCase);
}

注意事項與局限

  • 非標準 HTML:正則難以完美處理屬性值含 >、註釋 <!-- -->、CDATA、腳本/樣式內容等邊界情況。
  • 安全性:若輸入來自不可信源,單純去標簽無法防止 XSS,需使用成熟庫(如 HtmlSanitizer)做白名單清洗。
  • 性能:大文本頻繁調用建議預編譯 Regex 實例(static readonly Regex)。
  • 實體編碼:輸出可能殘留 &lt;、&nbsp; 等實體,視需求配合 HttpUtility.HtmlDecode 解碼。

總結

利用 Regex.Replace 配合 MatchEvaluator 回調,可靈活實現「移除 HTML 標簽但保留指定標簽(如 br)」的需求。代碼簡潔、無第三方依賴,適合輕量級場景。複雜或安全敏感場景請使用專業 HTML 解析/清洗庫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved