Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding modifiers to an existing regular expression

I have a bunch of regular expressions like lower = /[a-z]/ Later in my program i need to use this as /[a-z]/g ie. i need to add the 'global' modifier later. So how to add a modifier to an existing regular expression?

like image 382
Jinu Joseph Daniel Avatar asked Feb 24 '12 19:02

Jinu Joseph Daniel


People also ask

What is modifier in regular expression?

Regular expression patterns are often used with modifiers (also called flags) that redefine regex behavior. Regex modifiers can be regular (e.g. /abc/i ) and inline (or embedded) (e.g. (? i)abc ). The most common modifiers are global, case-insensitive, multiline and dotall modifiers.

What are modifiers in regular expression JavaScript?

The RegExp m Modifier in JavaScript is used to perform multiline matching. It takes the beginning and end characters (^ and $) as working when taken over multiple lines. It matches the beginning or end of each line. It is case-sensitive.

How do you add expressions in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


3 Answers

Use RegEx source and flags to separate the regular expression from the flags. Then create a new one with the string and set the needed flags.

var re = /^[a-z]*$/;
var re2 = new RegExp(re.source, re.flags + "i");

console.log( re.test("abc") )
console.log( re.test("ABC") )
console.log( re2.test("abc") )
console.log( re2.test("ABC") )
like image 76
epascarello Avatar answered Oct 02 '22 19:10

epascarello


Here is a function to build on epascarello's answer and the comments. You said you have quite a few of regexps to modify later on, you could just redefine the variable they are referenced in or make some new ones with a function call.

function modifyRegexpFlags(old, mod) {
    var newSrc = old.source;
    mod = mod || "";
    if (!mod) {
        mod += (old.global) ? "g" : "";
        mod += (old.ignoreCase) ? "i" : "";
        mod += (old.multiline) ? "m" : "";
    }
    return new RegExp(newSrc, mod);
}

var lower = /[a-z]/;
//Some code in-between
lower = modifyRegexpFlags(lower, "g");

If the second argument is omitted, the old modifiers will be used.
(Credit to davin for the idea).

like image 36
Chase Avatar answered Oct 02 '22 19:10

Chase


You can write a method for it-

RegExp.prototype.reflag= function(flags){
    return RegExp(this.source, flags);
}
like image 44
kennebec Avatar answered Oct 02 '22 18:10

kennebec