在 .NET 開發中,常需從 HTML 字符串中移除標籤或保留特定標籤。Regex.Replace 配合精心設計的模式可高效完成此任務。
protected void Page_Load(object sender, EventArgs e)
{
string htmlContent = GetHtmlContent(); // 獲取待處理 HTML
string pattern = @"<(?!img|br|p|/p).*?>"; // 保留 img, br, p 標籤
string cleanHtml = Regex.Replace(htmlContent, pattern, string.Empty, RegexOptions.IgnoreCase);
}
| 需求 | 正則模式 | 說明 |
|---|---|---|
| 移除所有標籤 | @"<[^>]*>" | 匹配任意標籤 |
| 移除 script 標籤及內容 | @"<script[^>]*?>.*?</script>" | 單行模式需加 RegexOptions.Singleline |
| 移除 img 標籤 | @"<img[^>]*>" | 針對圖片標籤 |
| 保留 br 標籤,移除其它 | @"<(?!br).*?>" | 負向前瞻排除 br |
| 移除 table 及其所有內容 | @"<table[^>]*?>.*?</table>" | 需 Singleline 選項 |
| 保留 img, br, p, /p | @"<(?!img|br|p|/p).*?>" | 多標籤排除 |
(?!...):負向前瞻斷言,匹配不後跟指定內容的位置.*?:非貪婪匹配,儘可能少匹配字符RegexOptions.IgnoreCase:忽略大小寫匹配RegexOptions.Singleline:讓 . 匹配換行符public string SanitizeHtml(string input, string[] allowedTags = null)
{
if (string.IsNullOrEmpty(input)) return string.Empty;
var allowed = allowedTags ?? new[] { "p", "br", "b", "i", "u", "strong", "em", "a" };
string allowedPattern = string.Join("|", allowed.Select(t => Regex.Escape(t)));
string pattern = $@"<(?!/?(?:{allowedPattern})\b)[^>]*>";
return Regex.Replace(input, pattern, string.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline);
}
> 等情況會導致匹配失敗// HtmlAgilityPack 示例
var doc = new HtmlDocument();
doc.LoadHtml(html);
var nodesToRemove = doc.DocumentNode.SelectNodes("//*[not(self::p or self::br or self::img)]");
if (nodesToRemove != null) {
foreach (var node in nodesToRemove) node.Remove();
}
return doc.DocumentNode.WriteTo();
正則適合簡單、可控場景;複雜 HTML 清理請使用專業解析器,安全與可維護性更有保障。