vaibhav
vaibhav

Reputation: 4103

Firefox throwing too complex error on compiling long words against the regex

I have a regex as below:

var str="checkedchec  ";
var patt=/.*(?:\w+|\S)*\s+(or|and|not|xnot|near|near\d+|onear|onear\d+|title\:|ingress\:|\?|\*|\^|sourceid\:|author\\:|url\:|country\:)\s+.*/i;

var newStr = str.split(patt);

var result=patt.test(str);

The above regex works fine mostly but when I have a character longer then 11 characters it gives "expression too complex" except on Mozilla firefox. It works fine on IE and Chrome.

Upvotes: 3

Views: 228

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

Your regex runs into catastrophic backtracking. You have alternating parts in it that can match the same thing (for example, every character matched by \w can also be matched by \S, and by the preceding .*) so the regex engine has to try oodles of permutations before declaring failure. RegexBuddy for example aborts the match attempt after 1 million steps of the regex engine, and Firefox is obviously doing the same (sensible) thing.

What exactly are you trying to do?

Changing the regex to

/.*\s+(or|and|not|xnot|near|near\d+|onear|onear\d+|title:|ingress:|\?|\*|\^|sourceid:|author:|url:|country:)\s+.*/i

speeds up the match a lot (now it's only 408 steps until the regex engine can declare failure).

Upvotes: 6

pimvdb
pimvdb

Reputation: 154958

It seems like your regexp can match in multiple ways.

It works if you change \w+ to \w. It is followed by * so why do you put a + here?

/.*(?:\w|\S)*\s+(or|and|not|xnot|near|near\d+|onear|onear\d+|title\:|ingress\:|\?|\*|\^|sourceid\:|author\\:|url\:|country\:)\s+.*/i

Upvotes: 0

Related Questions