5

I need to remove all style tags completely for the given HTML code. I found following regex to match entire style tag in the the XML. It works fine for the given Html code in online regex testers.

*style\s*=\s*('|")[^\2]*?\2([^>]*)*

However, through a C# code, it didn't work for the given HTML.

Following is the C# code:

Regex regex = new Regex("style\\s*=\\s*('|\")[^\\2]*?\\2([^>]*)", RegexOptions.IgnoreCase);
3

2 Answers 2

7

I usually use the below code to remove inline styles, class, images and comments from an Outlook message prior to saving it into database:

desc = Regex.Replace(desc, "(<style.+?</style>)|(<script.+?</script>)", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
desc = Regex.Replace(desc, "(<img.+?>)", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
desc = Regex.Replace(desc, "(<o:.+?</o:.+?>)", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
desc = Regex.Replace(desc, "<!--.+?-->", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
desc = Regex.Replace(desc, "class=.+?>", ">", RegexOptions.IgnoreCase | RegexOptions.Singleline);
desc = Regex.Replace(desc, "class=.+?\s", " ", RegexOptions.IgnoreCase | RegexOptions.Singleline);
1
6

Regex should be

 style\s*=\s*('|")[^\1]*\1

Though I would use Htmlagilitypack

   HtmlDocument doc = new HtmlDocument();
   doc.Load(yourStream);
   var elementsWithStyleAttribute = doc.DocumentNode.SelectNodes("//@style");
   foreach (var element in elementsWithStyleAttribute)
   {
       element.Attributes["style"].Remove();
   }
   doc.Save();
5
  • Modified regex doesnt work. I just need to remove only the style attribute.
    – Dimax
    Oct 12, 2013 at 11:39
  • @Dimax show the exact code you are using to replace and also a sample of that html
    – Anirudha
    Oct 12, 2013 at 11:43
  • Following is the code: Regex regex = new Regex("style\\s*=\\s*('|\")[^\\2]*?\\2([^>]*)", RegexOptions.Multiline | RegexOptions.IgnoreCase); htmldoc.Content = regex.Replace(htmldoc.Content, string.Empty); Sample Html Code: <P style="MARGIN: 0in 0in 0pt 0.5in" class="MsoNormal"> <SPAN style="FONT-FAMILY: 'Tw Cen MT Condensed Extra Bold'; COLOR: black; FONT-SIZE: 16pt; mso-bidi-font-family: Arial"> There are numerous applications </SPAN></P>
    – Dimax
    Oct 12, 2013 at 12:11
  • @Dimax u r not using regex in ans
    – Anirudha
    Oct 12, 2013 at 12:33
  • Hi Anirudh, sorry for the delay. i did the same using HtmlAgilityPack. Thnx for the sample code.
    – Dimax
    Nov 3, 2013 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.