Combining regular expressions in Javascript

JavascriptRegex

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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);

Solution 2 - Javascript

If regexps are not known beforehand,

var one = /[a-z]/;
var two = /[A-Z]/;

var one_or_two = new RegExp("(" + one.source + ")|(" + two.source + ")")

Solution 3 - Javascript

use a general function:

const getComposedRegex = (...regexes) => new RegExp(regexes.map(regex => regex.source).join("|"))

Then call it with any number of Regexes.

const reg1 = /[w]{3}/i
const reg2 = /http/i

const composedReg = getComposedRegex(reg1, reg2)

Solution 4 - Javascript

If this is something you only need to do once or twice, I'd stick with doing it on a per-case basis as suggested by other answers.

If you need to do a lot, however, a couple of helper functions might improve readability. For example:

var lower = /[a-z]/,
    upper = /[A-Z]/,
    digit = /[0-9]/;

// All of these are equivalent, and will evaluate to /(?:a-z)|(?:A-Z)|(?:0-9)/
var anum1 = RegExp.any(lower, upper, digit),
    anum2 = lower.or(upper).or(digit),
    anum3 = lower.or(upper, digit);

And here's the code if you want to use those functions:

RegExp.any = function() {
    var components = [],
        arg;
    
    for (var i = 0; i < arguments.length; i++) {
        arg = arguments[i];
        if (arg instanceof RegExp) {
            components = components.concat(arg._components || arg.source);
        }
    }
   
    var combined = new RegExp("(?:" + components.join(")|(?:") + ")");
    combined._components = components; // For chained calls to "or" method
    return combined;
};

RegExp.prototype.or = function() {
    var args = Array.prototype.slice.call(arguments);
    return RegExp.any.apply(null, [this].concat(args));
};

The alternatives are wrapped in non-capturing groups and combined with the disjunction operator, making this a somewhat more robust approach for more complex regular expressions.

Note that you will need to include this code before calling the helper functions!

Solution 5 - Javascript

Based on Bry6n answer here's a solution I use:

const Regexes = {
  Empty: /^$/,
  Minus: /^[-]$/,
  DotAndNumber: /^\.\d+$/,
  NumberAndDot: /^\d+\.$/,
  Float: /^[-]?\d+(\.\d+)?$/,
};

const orRegex = (...regexes) =>
  new RegExp(regexes.map(r => r.source).join('|'));

const FloatInputRegex = orRegex(
  Regexes.Empty,
  Regexes.Minus,
  Regexes.DotAndNumber,
  Regexes.NumberAndDot,
  Regexes.Float,
);

Solution 6 - Javascript

alpha = new RegExp( lower.source + "|" + upper.source );
console.log( alpha );
// /[a-z]|[A-Z]/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJinu Joseph DanielView Question on Stackoverflow
Solution 1 - JavascriptBry6nView Answer on Stackoverflow
Solution 2 - JavascriptgeorgView Answer on Stackoverflow
Solution 3 - JavascriptBen CarpView Answer on Stackoverflow
Solution 4 - JavascriptJordan GrayView Answer on Stackoverflow
Solution 5 - JavascriptSebastien LorberView Answer on Stackoverflow
Solution 6 - JavascriptEsailijaView Answer on Stackoverflow