Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript hang when matching regular expression using IE & Chrome

I got a bugged regex "\w+([\.\-]?\w+)*@" when it try to test whether it matchs a string

"ffffffffffb3ffffffffffafffffffffffabffffffffffc2ffffffffffa7e"

it will cause IE and Chrome hung up. But works fine by FF.

I found out that the "?" in the regex is not necessary. And it works find after I remove the "?".

But here is what I don't understand what cause the problem. Here is some test

  1. "\w+([\.\-]?\w+)*" works fine.

  2. "\w+([\.\-]\w+)*@" works fine.

  3. "\w+([\.\-]?\w+)*@" cause the problem

Anyone knows why? or it's just the performance between browsers.

like image 510
Jack Cheng Avatar asked Nov 16 '25 21:11

Jack Cheng


1 Answers

This is called catastrophic backtracking.

In your third example, the @ (which obviously causes the regex to fail) forces your regex engine to try all possible permutations of \w+(\w+)* (since the character class is optional). With a string of this length, the calculations would take longer than until the heat death of the universe.

RegexBuddy Screenshot

Firefox appears to have an iteration limit on regexes and will abort after about a million attempts, Chrome and IE seem to be a bit more stoic here.

like image 111
Tim Pietzcker Avatar answered Nov 19 '25 11:11

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!