【问题标题】:New Regex from literate string [duplicate]来自识字字符串的新正则表达式 [重复]
【发布时间】:2021-01-12 01:56:44
【问题描述】:

我不明白为什么rg = new RegExp(`/${a}.*${b}/`) 在下面不起作用而rg = /\(.*\)/ 起作用。

let a = '\(';
let b = '\)';
let rg;
//rg = new RegExp(`/${a}.*${b}/`); // doesn't work
rg = /\(.*\)/;
let match = rg.exec(`test (regex works) is ok`);
if (match) {
  console.log(match[0]); // -> (regex works)
}

【问题讨论】:

    标签: javascript regex typescript


    【解决方案1】:

    因为您需要对字符串中的\ 进行双重转义。

    let a = '\\(';
    let b = '\\)';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 2020-05-06
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      相关资源
      最近更新 更多