Javascript 正则表达式 - 字符串到 RegEx 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4589587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:14:01  来源:igfitidea点击:

Javascript regular expression - string to RegEx object

javascriptregex

提问by shake

I am sure its something pretty small that I am missing but I haven't been able to figure it out.

我确信它是我遗漏的很小的东西,但我一直无法弄清楚。

I have a JavaScript variable with the regex pattern in it but I cant seem to be able to make it work with the RegEx class

我有一个带有正则表达式模式的 JavaScript 变量,但我似乎无法使其与 RegEx 类一起使用

the following always evaluates to false:

以下总是评估为假:

var value = "[email protected]";
var pattern = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"
var re = new RegExp(pattern);
re.test(value);

but if I change it into a proper regex expression (by removing the quotes and adding the /at the start and end of the pattern), it starts working:

但是如果我将其更改为适当的正则表达式(通过删除引号并/在模式的开头和结尾添加),它就会开始工作:

var value = "[email protected]";
var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/
var re = new RegExp(pattern);
re.test(value);

since I always get the pattern as a string in a variable, I haven't been able to figure out what I am missing here.

由于我总是将模式作为变量中的字符串获取,因此我无法弄清楚我在这里遗漏了什么。

回答by RoToRa

Backslashes are special characters in strings that need to be escaped with another backslash:

反斜杠是字符串中需要用另一个反斜杠转义的特殊字符:

var value = "[email protected]";
var pattern = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"
var re = new RegExp(pattern);
re.test(value);