Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining regular expressions in Javascript

Is it possible to combine regular expressions in javascript.

For ex:

 var lower = /[a-z]/;  var upper = /[A-Z]/;  var alpha = upper|lower;//Is this possible? 

ie. can i assign regular expressions to variables and combine those variables using pattern matching characters as we do in regular expressions

like image 830
Jinu Joseph Daniel Avatar asked Feb 09 '12 15:02

Jinu Joseph Daniel


People also ask

How do you combine two regular expressions?

to combine two expressions or more, put every expression in brackets, and use: *? This are the signs to combine, in order of relevance: ?

Does regex work in JavaScript?

In JavaScript, you can write RegExp patterns using simple patterns, special characters, and flags.

What is RegExp test in JavaScript?

JavaScript RegExp test() The test() method tests for a match in a string. If it finds a match, it returns true, otherwise it returns false.


Video Answer


2 Answers

The answer is yes! You have to initialize the variable under the RegExp class:

var lower = new RegExp(/--RegexCode--/); var upper = new RegExp(/--RegexCode--/); 

hence, regex can be dynamically created. After creation:

"sampleString".replace(/--whatever it should do--/); 

Then you can combine them normally, yes.

var finalRe = new RegExp(lower.source + "|" + upper.source); 
like image 165
Bry6n Avatar answered Sep 19 '22 19:09

Bry6n


If regexps are not known beforehand,

var one = /[a-z]/; var two = /[A-Z]/;  var one_or_two = new RegExp("(" + one.source + ")|(" + two.source + ")") 
like image 45
georg Avatar answered Sep 19 '22 19:09

georg