Adding modifiers to an existing regular expression

最后都变了- 提交于 2020-04-06 02:07:46

问题


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?


回答1:


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



回答2:


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




回答3:


You can write a method for it-

RegExp.prototype.reflag= function(flags){
    return RegExp(this.source, flags);
}



回答4:


One aspect not really covered in earlier answers, so adding my two cents...

The excellent answers (+1 for epascarello!) here don't quite cover all the bases. If you want to generalize the function to allow any flags added to any regex:

function addregexflags(regx, newflags) {
    // add new flags without duplication (won't work in old browsers or IE)
    newflags = [...new Set([...regx.flags.split(''), ...newflags.split('')])].join('');
    return new RegExp(regx.source, newflags);
}

addregexflags(/try/gi, "gm");    // /try/gim

If you have to support older browsers that don't support Sets and the spread operator, you need to longhand the union of strings as the RegExp constructor does not allow replication of flags.



来源:https://stackoverflow.com/questions/9437203/adding-modifiers-to-an-existing-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!