如何动态操作正则表达式的模式



>我有一个文本lines数组和一个terms数组,每个term行都包含一对单词。 例如,terms数组可以是这样的:

blue, red
high, low
free, bound
 ...

对于lines数组中的每一行,我需要遍历所有terms的列表,并将第一个单词的每个出现替换为第二个单词;全局且不区分大小写。例如,行

The sky is Blue and High, very blue and high, yet Free

会成为

The sky is red and low, very red and low, yet bound

像这样的代码:

function filter(lines,terms){
    for (line of lines){
        for (term of terms){
             tofind    = term[0]; //this is a string not RegExp
                                  //still needs the 'gi' flags
             toreplace = term[1];
             line      = line.replace(tofind,toreplace);
        }
    }
}

这是错误的,因为tofind需要是 RegExp(模式,"gi"(,并且需要在循环内的每次迭代中动态生成。

如果tofind字符串是静态的,我们可以这样做:

line = line.replace(/some-static-text-here/gi,toreplace)

我尝试了line.replace(new RegExp(tofind,'gi'),toreplace)但这抛出了一个错误Invalid regular expression: /*Contains/: Nothing to repeat

所以,问题是:如何在循环内动态修改 RegExp 对象的模式?

如果术语数组仅包含字母数值,则可以构建新的正则表达式。

function filter(lines, terms) {
    return lines.map(s => 
        terms.reduce((r, t) => r.replace(new RegExp(t[0], 'gi'), t[1]), s));
}
console.log(filter(['The sky is Blue and High, very blue and high, yet Free'], [['blue', 'red'], ['high', 'low'], ['free', 'bound']]));

最新更新