简体   繁体   中英

Maximum size/length of regular expression in “modern” web browsers?

What's the maximum size of a regular expression in modern browsers (ie Firefox 3+, Safari 4+, IE 7+)? Assume a simple regular expression, of, say "foo|bar|baz|woot|..."

You can use this code to test, in IE8 / firefox with firebug / Chrome.

var regex = "";
var maximum = 100;
var showAfter = 95;
for(i = 1; i < maximum; i++) {
    regex += "aaaaaaaaaa";
    if (i > showAfter) {
        console.log(10 * i + " chars");
        console.log(RegExp(regex));
    }
}

When you get a error, you found the limit.


SIMPLE TEST

var regex = "";
var chars = 3204161;
for(i = 0; i < chars; i++) {
    regex += "a";
}
alert(chars + " chars");
var a = RegExp(regex); // don't send to console, to be faster

RESULTS

In Firefox 3.6.3 (Ubuntu 32 bits) I get error when I tried a regex with 9M chars (9.999.990 chars) 3.204.161 chars. With 3.204.160 it's ok.

In Chrome 5.0.3 the limit is something between 20M and 25M chars.

The error, in firefox, is:

script stack space quota is exhausted

Note: If you did some test, please comment here.

Certain regular expressions require exponential amounts of memory to evaluate. Since Firefox does this on the stack, which is limited to 10 MB on many Linux distributions, and even smaller in Windows (at least some versions of Firefox), you could hit the limit fairly quickly if you use a regular expression that requires exponential memory to convert to DFA form to evaluate.

If your regular expression is simple like that, why not just have a loop that does string comparisons:

var input = "woot";

var tests = ["foo", "bar", "baz", "woot"];
for(i = 0; i < tests.length; i++) {
   if (tests[i] == input) {
      alert("match found: #" + i);
      break;
   }
}

Then you don't have to worry about browser limitations, and it'll likely perform much better as a result (since the regular expression version would have to parse and compile the regex, there'd be plenty of back tracking, and so on).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM