// 1. 移除所有標籤(含屬性)
string patternAll = @"<[^>]*>";
// 2. 移除 script 標籤及內容
string patternScript = @"";
// 3. 移除 iframe 標籤及內容
string patternIframe = @"";
// 4. 移除 style 標籤及內容
string patternStyle = @"";
// 5. 移除所有標籤,但保留
string patternKeepBr = @"<(?!br\b)[^>]*>";
// 6. 移除所有標籤,保留
string patternKeepSelected = @"<(?!img|br|p|/p\b)[^>]*>";
// 7. 移除 table 及其所有內容
string patternTable = @"]*>.*?
";
string input = "..."; // 含 HTML 的字符串
// 組合過濾:先去腳本/樣式,再去其餘標籤(保留安全集)
string step1 = Regex.Replace(input, patternScript, "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
string step2 = Regex.Replace(step1, patternIframe, "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
string step3 = Regex.Replace(step2, patternStyle, "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
string clean = Regex.Replace(step3, patternKeepSelected, "", RegexOptions.IgnoreCase);
RegexOptions.IgnoreCase:大小寫不敏感匹配標籤名。RegexOptions.Singleline:讓 `.` 匹配換行符,跨行匹配標籤內容。(?!xxx):負向前瞻,排除指定標籤。var doc = new HtmlDocument();
doc.LoadHtml(html);
foreach (var node in doc.DocumentNode.SelectNodes("//script|//style|//iframe").ToList())
node.Remove();
// 保留白名單標籤,其餘展平為文本
var allowed = new HashSet { "p", "br", "b", "strong", "em", "a", "img" };
foreach (var node in doc.DocumentNode.Descendants().Where(n => n.NodeType == HtmlNodeType.Element).ToList())
{
if (!allowed.Contains(node.Name))
{
node.ParentNode.ReplaceChild(HtmlNode.CreateNode(node.InnerText), node);
}
}
string safeHtml = doc.DocumentNode.OuterHtml;
正則適合簡單、可控、一次性清洗;複雜、不可信、長期維護的 HTML 淨化,**請用專業解析器**。