將富文本 HTML 字符串「去標簽化」為純文本,但保留 <br> 換行標簽(或轉換為環境換行符),其他標簽(如 <div>、<b>、<style> 等)全部移除。
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);
}
>、註釋 <!-- -->、CDATA、腳本/樣式內容等邊界情況。Regex 實例(static readonly Regex)。<、 等實體,視需求配合 HttpUtility.HtmlDecode 解碼。利用 Regex.Replace 配合 MatchEvaluator 回調,可靈活實現「移除 HTML 標簽但保留指定標簽(如 br)」的需求。代碼簡潔、無第三方依賴,適合輕量級場景。複雜或安全敏感場景請使用專業 HTML 解析/清洗庫。