The fragment below doesn't work for me.
fragment = Regex.Replace(fragment, "<!--.*?-->", String.Empty , RegexOptions.Multiline );
The fragment below doesn't work for me.
fragment = Regex.Replace(fragment, "<!--.*?-->", String.Empty , RegexOptions.Multiline );
Please don't use regular expressions to work with markup languages - you need to use a better tool that is built for that kind of job.
Use the Html Agiliy Pack instead. I even found this article in which a reader (named Simon Mourier) comments with a function that uses the Html Agility Pack to remove comments from a document:
Simon Mourier said:
This is a sample code to remove comments:
static void Main(string[] args) { HtmlDocument doc = new HtmlDocument(); doc.Load("filewithcomments.htm"); doc.Save(Console.Out); // show before RemoveComments(doc.DocumentNode); doc.Save(Console.Out); // show after } static void RemoveComments(HtmlNode node) { if (node.NodeType == HtmlNodeType.Comment) { node.ParentNode.RemoveChild(node); return; } if (!node.HasChildNodes) return; foreach(HtmlNode subNode in node.ChildNodes) { RemoveComments(subNode); } }
This one works for me:
<!--(\n|.)*-->
But I think you could use normal XML document for the XML or otherwise HtmlAgilityPack for HTML. Highly not recommending to parse markup using RegEx.
http://www.codeplex.com/htmlagilitypack
SUMMARY: It is a .NET code library that allows you to parse "out of the web" HTML files. The parser is very tolerant with "real world" malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).
Have a look at - http://stackoverflow.com/questions/787932/using-c-regular-expressions-to-remove-html-tags
Change it to RegExOptions.Singleline
instead and it'll work just fine.
When not in Singleline mode, the dot matches any character, except newline.
Note that Singleline
and Multiline
are not mutually exclusive. They do two separate things. To quote MSDN:
Multiline mode. Changes the meaning of ^ and $ so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire string.
Single-line mode. Changes the meaning of the dot (.) so it matches every character (instead of every character except \n).
Other people have already suggested the HTML Agility Pack. I just felt you should have an explanation on why your Regex wouldn't work :)