4

This is not what I'm asking for:

concatenate multiple regexes into one regex

Is there a way to append a regex into another one (in JavaScript language) ?

The reason for doing so is to simplify code maintenance (e.g. if the included string is long or easier to maintain by a non-programmer).

In Python, for example, i'd write something like:

regstr1 = 'dogs|cats|mice'
regstr_container = '^animal: (cows|sheep|%s|zebra)$' % regstr1
re.compile(regstr_container)

however, in JavaScript, the regular expression is not a string.

re = /^animal: (rami|shmulik|dudu)$/;

or am I missing something?

Alex
  • 1,457
  • 1
  • 13
  • 26
Berry Tsakala
  • 15,313
  • 12
  • 57
  • 80
  • i've closed this question; but didn't delete it so others that use the keywords i've used will reach this link: http://stackoverflow.com/questions/185510/how-can-i-concatenate-regex-literals-in-javascript – Berry Tsakala Aug 23 '09 at 15:54

2 Answers2

6

You don't have to use the literal notation. You could instead create a new RegExp object.

var myRegex = new RegExp("^animal: (rami|shmulik|dudu)$");
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • +1, and you can make a placeholder: container = "...(cows|sheep|{BLAH}|zebra).."; var re = new Regexp(container.replace("{BLAH}", regstr1); – orip Aug 23 '09 at 17:06
3
var regstr1 = 'dogs|cats|mice',
regstr_container = '^animal: (cows|sheep|'+ regstr1 +'|zebra)$',
regex = RegExp(regstr_container);
Eli Grey
  • 35,104
  • 14
  • 75
  • 93