如何将字符串化的正则表达式文字转换回正则表达式?

Chu*_* Fu 3 javascript regex literals regex-group

例如,我在客户端从服务器获取了一个字符串:

"/hello\s{0,1}[-_.]{0,1}world|ls\b/gim"
Run Code Online (Sandbox Code Playgroud)

在客户端,我想将此字符串转换为正则表达式对象。我试过

new RegExp("/hello\s{0,1}[-_.]{0,1}world|ls\b/gim")
Run Code Online (Sandbox Code Playgroud)

但这行不通,返回的对象是

/\/hellos{0,1}[-_.]{0,1}world|ls\/gim/
Run Code Online (Sandbox Code Playgroud)

总结一下:我想要的是:

/hello\s{0,1}[-_.]{0,1}world|ls\b/gim.test('hello world') //true (correct behavior)
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用:

new RegExp("/hello\s{0,1}[-_.]{0,1}world|ls\b/gim").test('hello world') //false
Run Code Online (Sandbox Code Playgroud)

这样做的正确方法是什么?

gyr*_*yre 5

RegExp构造函数有两个参数。第一个是要匹配的文字源/模式(本质/上是正则表达式文字中外部之间的内容);第二个是要在该表达式上设置的标志(例如gim在您的示例中)。我在下面为您定义了一个辅助函数,它将您的格式中的字符串转换为正则表达式。具有讽刺意味的是,我最终使用了另一个正则表达式来做到这一点。

function regexFromString (string) {
  var match = /^\/(.*)\/([a-z]*)$/.exec(string)
  return new RegExp(match[1], match[2])
}

var string = '/hello\\s{0,1}[-_.]{0,1}world|ls\\b/gim'

var regex = regexFromString(string)

console.log(regex instanceof RegExp) //=> true
console.log(regex)
console.log(regex.test('hello world')) //=> true
Run Code Online (Sandbox Code Playgroud)