Wednesday, March 28, 2012

string.remove and while

I have the following method that should remove html comments. But it's not reacting the way I expect. When the loop breaks and I return the string, I get the correct value - all comments are removed. But the loop will not break using neither the while conditional statement or the internal IndexOf check, therefore stuck in an infinite loop (save for the counter that breaks it).

What am I missing??

public static string RemoveComments(string page) {int i = 0;while (page.IndexOf("<!--") > 0) {int _CommentStart = page.IndexOf("<!--");int _CommentEnds = page.IndexOf("-->");if (_CommentStart > 0) {if (_CommentEnds <= _CommentStart) {break; } page.Remove(_CommentStart, (_CommentEnds - _CommentStart)); }if (page.IndexOf("<!--") < 1) { i = 100; } i++;if (i > 10)break; }return page +" " + i.ToString(); }
I'm not following that logic too well - I don't use c# either - but wouldn't this be a case for regular expressions ?
I'm not a regular expressions expert, but I'm sure there is a way to look for that string and remove it.
Do a search on using regular expressions...

Thank you, very good suggestion. I used the following:

System.Text.RegularExpressions.Regex r =new System.Text.RegularExpressions.Regex(@."\<![ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\>");return r.Replace(page,string.Empty);

0 comments:

Post a Comment