Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中将字符串转换为正则表达式_Javascript_Regex_Node.js - Fatal编程技术网

如何在javascript中将字符串转换为正则表达式

如何在javascript中将字符串转换为正则表达式,javascript,regex,node.js,Javascript,Regex,Node.js,例如,我在客户端从服务器获取了一个字符串: "/hello\s{0,1}[-_.]{0,1}world|ls\b/gim" 在客户机中,我想将该字符串转换为正则表达式对象。我试过了 new RegExp("/hello\s{0,1}[-_.]{0,1}world|ls\b/gim") 但这不起作用,返回的对象是 /\/hellos{0,1}[-_.]{0,1}world|ls\/gim/ 总结如下: 我想要的是: /hello\s{0,1}[-_.]{0,1}world|ls\b/gim.

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

"/hello\s{0,1}[-_.]{0,1}world|ls\b/gim"
在客户机中,我想将该字符串转换为正则表达式对象。我试过了

new RegExp("/hello\s{0,1}[-_.]{0,1}world|ls\b/gim")
但这不起作用,返回的对象是

/\/hellos{0,1}[-_.]{0,1}world|ls\/gim/
总结如下: 我想要的是:

/hello\s{0,1}[-_.]{0,1}world|ls\b/gim.test('hello world') //true (correct behavior)
但是,这不起作用:

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

正确的方法是什么?

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

函数regexFromString(string){
var match=/^\/(.*)\/([a-z]*)$/.exec(字符串)
返回新的RegExp(匹配[1],匹配[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
使用
RegExp
构造函数有点不同,以下是我认为您需要的:

var x = new RegExp('hello\\s{0,1}[-_.]{0,1}world|ls\\b', 'gim').test("hello world");

console.log(x);

返回true

为什么不传递一个regexp并省去额外的转义呢?您的脚本是否处理嵌入的斜杠?(不^ |$)1)用OP的话来说:“我从服务器的客户端获得了一个字符串”。他没有得到正则表达式;因此,在我的代码片段中,我也不是从一个开始。2) 我明白你的意思了。几乎错过了,谢谢你的指针。嘿:
eval(“/hello\\s{0,1}[-\.]{0,1}world | ls\\b/gim”)。test('hello world')
因为你有正则表达式语法(而不是字符串语法),你不能直接在正则表达式构造函数中使用它。您可以将其与
eval()
一起使用。