Reputation: 3462
Suppose that I have a very large string str
and I need to execute multiple regex patterns on str
, is there anyway I can do this in javascript such that the total running time depends only on the length of the string but not on the number of regex patters?
i.e. instead of doing the following
var match1 = myRegexp1.exec(str);
var match2 = myRegexp2.exec(str);
var match3 = myRegexp3.exec(str);
is there any way to execute all the regex patterns at a time on the string.
I found an article http://fulmicoton.com/posts/multiregexp/ which says that there is re2 for C++ and he(the guy who wrote the article) made the library for Java. Is there any such for/in Javascript?
Upvotes: 2
Views: 2974
Reputation: 59232
I suppose you need something like this
var rgx = new RegExp([myRegexp1, myRegexp2, myRegexp3].map(function(r){
return (r+"").replace(/\//g,"");
}).join("|"), "g");
var match = rgx.exec(str);
What it does is take your regex and remove delimiters and join it with |
so it becomes multiple regex and finally add a global flag.
Upvotes: 1