Combining regular expressions in Javascript

后端 未结 6 1294
-上瘾入骨i
-上瘾入骨i 2020-11-27 05:22

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          


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 06:14

    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!

提交回复
热议问题