正则表达式删除正文标记属性(C#)

任何人都有一个可以从body标签中删除属性的正则表达式

例如:

 

回来:

  

看到仅删除特定属性的示例也很有趣,例如:

  

回来:

  

你不能用正则表达式解析XHTML 。 请改为查看HTML Agility Pack 。

 HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); HtmlNode body = doc.DocumentNode.SelectSingleNode("//body"); if (body != null) { body.Attributes.Remove("style"); } 

如果你正在做一个快速而又脏的shell脚本,并且你不打算使用这么多……

 s/]*>// 

但是我必须同意其他人的观点,解析器是一个更好的主意。 我知道有时你必须用有限的资源来做,但是如果你依赖于一个正则表达式……它很有可能在你最不期望的时候回来咬你。

并删除特定属性:

 s/\(]*\) style="[^>"]*"/\1/ 

这将获取“body”和任何属性直到“style”,删除“style”属性,然后吐出其余的。

使用正则表达式的三种方法…

 string html = ""; string a1 = Regex.Replace(html, @"(?<=)", ""); string a2 = Regex.Replace(html, @"<(body)\b.*?>", "<$1>"); string a3 = Regex.Replace(html, @"<(body)(\s[^>]*)?>", "<$1>"); Console.WriteLine(a1); Console.WriteLine(a2); Console.WriteLine(a3); 

上面的LittleBobbyTables评论是正确的!

正则表达式不是正确的工具,如果你读它,它实际上是正确的,使用正则表达式来处理这种事情将会给你带来过度压力和压力,因为答案清楚地显示在LittleBobbyTables发布的链接上,回答者所经历的是什么错误工具使用错误工具的结果。

正则表达式不是用于执行此类操作的胶带,也不是包括42在内的所有内容的答案… 使用正确的工具来完成正确的工作

但是你应该查看HtmlAgilityPack ,它将为你完成这项工作,并最终通过使用正则表达式来解析html,从而避免因压力,眼泪和血液而导致的死亡……

这是你在SharpQuery中的表现

 string html = ""; var sq = SharpQuery.Load(html); var body = sq.Find("body").Single(); foreach (var a in body.Attributes.ToArray()) a.Remove(); StringWriter sw = new StringWriter(); body.OwnerDocument.Save(sw); Console.WriteLine(sw.ToString()); 

这取决于HtmlAgilityPack并且是测试版产品……但我想certificate你可以这样做。

 string pattern = @"]*>"; string test = @""; string result = Regex.Replace(test,pattern,"",RegexOptions.IgnoreCase); Console.WriteLine("{0}",result); string pattern2 = @"(?<=]*)\s*style=""[^""]*""(?=[^>]*>)"; result = Regex.Replace(test, pattern2, "", RegexOptions.IgnoreCase); Console.WriteLine("{0}",result); 

这是为了防止您的项目要求限制您的第三方选项(并且没有给您时间重新发明解析器)。

我目前正在工作的厚实代码,将考虑减少这个:

 private static string SimpleHtmlCleanup(string html) { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); //foreach(HtmlNode nodebody in doc.DocumentNode.SelectNodes("//a[@href]")) var bodyNodes = doc.DocumentNode.SelectNodes("//body"); if (bodyNodes != null) { foreach (HtmlNode nodeBody in bodyNodes) { nodeBody.Attributes.Remove("style"); } } var scriptNodes = doc.DocumentNode.SelectNodes("//script"); if (scriptNodes != null) { foreach (HtmlNode nodeScript in scriptNodes) { nodeScript.Remove(); } } var linkNodes = doc.DocumentNode.SelectNodes("//link"); if (linkNodes != null) { foreach (HtmlNode nodeLink in linkNodes) { nodeLink.Remove(); } } var xmlNodes = doc.DocumentNode.SelectNodes("//xml"); if (xmlNodes != null) { foreach (HtmlNode nodeXml in xmlNodes) { nodeXml.Remove(); } } var styleNodes = doc.DocumentNode.SelectNodes("//style"); if (styleNodes != null) { foreach (HtmlNode nodeStyle in styleNodes) { nodeStyle.Remove(); } } var metaNodes = doc.DocumentNode.SelectNodes("//meta"); if (metaNodes != null) { foreach (HtmlNode nodeMeta in metaNodes) { nodeMeta.Remove(); } } var result = doc.DocumentNode.OuterHtml; return result; }