Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove comment block <!-- --> from string in C#

Tags:

string

c#

regex

How can I remove comment blocks in a string. This is a part of my string that I want to remove.

<!--
[if !mso]> <style> v\:* {behavior:url(#default#VML);} o\:*    {behavior:url(#default#VML);} w\:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} </style> <![endif]

-->
like image 239
Azade Avatar asked Sep 16 '26 12:09

Azade


2 Answers

I found a regex to remove this kind of comment block

myString = Regex.Replace(myString , @"(?s)(?<=<!--).+?(?=-->)", "")
like image 94
Azade Avatar answered Sep 19 '26 01:09

Azade


in these cases I'd advice you to use an external lib such as "Html Agility Pack" http://htmlagilitypack.codeplex.com/ It's availble via NuGet & on their codeplex page you'll find code examples on houw to use the library.

It will enable you to load the html model in C#. By that you can pull out the things you don't need, or manipulate certain tags etc.. etc.. Or even, such as in your case, extract the comments inside an html-doc. I don't have the exact code snippet for your case, but you'll be able to work it out very fast with this library.

Doing this yourself, even with REGEX, will cost a lot of time implementing and will be error prone at first. Look at it like this: don't reinvent the wheel ;).

like image 33
Yves Schelpe Avatar answered Sep 19 '26 03:09

Yves Schelpe