Javascript正则表达式-RegEx对象的字符串 [英] Javascript regular expression - string to RegEx object
问题描述
我确定它确实很小,但是我无法弄清楚.
I am sure its something pretty small that I am missing but I haven't been able to figure it out.
我有一个带有regex模式的JavaScript变量,但我似乎无法使其与RegEx类一起工作
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
以下内容始终为false:
the following always evaluates to false:
var value = "someone@something.com";
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 = "someone@something.com";
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.
推荐答案
反斜杠是字符串中的特殊字符,需要用另一个反斜杠转义:
Backslashes are special characters in strings that need to be escaped with another backslash:
var value = "someone@something.com";
var pattern = "^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$"
var re = new RegExp(pattern);
re.test(value);
这篇关于Javascript正则表达式-RegEx对象的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!