[thelist] Regular Expression - Is it a bug or am I missing something very obvious?

Edwin Martin edwin at bitstorm.org
Thu Mar 10 04:08:57 CST 2005


>Regarding the following js reg exp.
>/<\/?(?!(p))/ig;   (It's a simplified version of what I'm working on)
>I think what it is supposed to do is:
>1. match character < literally
>2. match craracter / literally (zero or one times)
>3. If there is a p immediately after do not match anything, just
>rollback (i.e. negative lookahead)
>so the code below
>var strTest1 = "</p>";
>var regEx1 = /<\/?(?!(p))/ig;
>strTest1 = strTest1.replace(regEx1,"")
>should alert "</p>".
>Well it doesn't. It alerts "p/>". Which means that it has found a match.
I think this happens:

1) It tries to match <. Match.
2) It tries to match  /. Match.
3) Next char must not match p. It is, so no match, rollback.
4) It tries to macht zero occurances of /. Match.
5) Next char must not match p. Next char is /, so you have a match.

The string "<" is matched, so it is replaced with "" and the result is 

Edwin Martin


More information about the thelist mailing list