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|ht开发者_如何学Goml|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">A Link containing 'HTML'</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...
i am not sure how you do this in C# but it seems that you forgot to make your regexp case insensitive.
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
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
精彩评论