2

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?

7
  • Do you want to execute them all or fail on the first match/no-match? Are the regular expressions constant? If so what are they? Commented Dec 10, 2014 at 14:19
  • @AlexK. I want to execute them all... i am trying to parse the html content of a page with each regex for each case i am having.. and in oe particular execution the regexps are constant Commented Dec 10, 2014 at 14:21
  • Parsing HTML with JavaScript is easier when you use DOM :) Commented Dec 10, 2014 at 14:24
  • There are better ways of parsing html in JavaScript than RegExs ... Commented Dec 10, 2014 at 14:24
  • @Ja͢ck, Alex Hmm yeah but here in my case i only have some input which would be present inside a div and i need to remove that div Commented Dec 10, 2014 at 14:28

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

this isn't working fine if the regex has escape character... i.e for eg [/\<nllm/, /road/] is being converted as /\\<nllm|road/g instead of /\<nllm|road/g
not sure why but only the 2nd regex in array is working after merge

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.