tags:

views:

89

answers:

4

Yes I know its usually a bad idea to parse HTML using RegEx, but that aside can someone explain the fault here:

 string outputString = Regex.Replace(inputString, @"<?(?i:script|embed|object|frameset|frame|iframe|metalink|style|html|img|layer|ilayer|meta|applet)(.|\n)*?>", "");
if (outputString != inputString)
{
   Console.WriteLine("unwanted tags detected");
}

It certainly detects the intended tags like: <script> and <html>, but it also rejects strings I want to allow such as <B>Description</B> and <A href="http://www.mylink.com/index.html"&gt;A Link containing 'HTML'</A>

+1  A: 

i am not sure how you do this in C# but it seems that you forgot to make your regexp case insensitive.

Nir Levy
Actually he didn't the expression `(?i:...)` makes the RegEx case insensitive in that part.
Paulo Santos
right. my bad. C# is not my native regexp engine..
Nir Levy
+1  A: 

From what I see it just need a little nudge:

Change from

"<?(?i:script|...|applet)(.|\n)*?>"

to

"\<(?i:script|...|applet)(.|\n)*?\>"

As the characters < and > are special

Paulo Santos
I tried it, but sorry that doesn't work - :(
Tom Brown
No, `<` and `>` do not have special meaning in regexes. In fact, in flavors you *give* them special meaning by adding backslashes: `\<` matches the beginning of a word and `\>`, the end of a word.
Alan Moore
+2  A: 

I think the problem is the first question mark in

<?(?i:script

You probably want to match the leading "/" character in a closing html-tag, right? I think the question mark makes the "<" optional (zero or one match).

I suggest using

<(/)?(?i:script

but I am no RegEx-expert...

scherand
Thanks this worked well.
Tom Brown
Correct, but you don't need the parentheses; `</?` works just fine.
Alan Moore
A: 

I would change

"<?(?i:script|...|meta|applet)(.|\n)*?>"

to

"</?(?:script|...|meta|applet)[^>]*>"

I am not totally familiar with Javascript Regex strings, but I do have a reference and I am familiar with regex basics (and once in a while I need a refresher).

the \s is entirely optional - it is not needed. you can keep it in if you wish. note that this does NOT handle uppercase tags. you will need to handle those as additional cases.

you may have to escape the / in the string. you don't need a ? after the * because * means 0 to many, so that covers optional.

I am not sure, but I don't think the greedy * will overtake the (?:).

http://www.regular-expressions.info/quickstart.html

Jim Michaels