使用 new RegExp("regex");
和 /same_regex/
来测试目标字符串有什么区别吗?我问这个问题是因为我在使用这两种方法时得到了不同的验证结果。这是我用来验证电子邮件字段的片段:
var email="didxga@gmail.comblah@foo.com";
var regex1 = new RegExp("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
var regex2 = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
//using RegExp object
if(regex1.test(email)) {
console.log("email matched regex1");
} else {
console.log("email mismatched regex1");
}
//using slash notation
if(regex2.test(email)) {
console.log("email matched regex2");
} else {
console.log("email mismatched regex2");
}
我得到了两个不一致的结果:
email matched regex1 email mismatched regex2
我想知道这里是否有任何区别,或者我在这个特定示例中遗漏了什么?
有关可执行示例,请参阅 here
最佳答案
如果您使用构造函数创建一个新的 RegExp 对象而不是文字语法,您需要正确转义 \
:
new RegExp("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$")
这是必要的,因为在 JavaScript 中任何未知的转义序列 \x
都被解释为 x
。所以在这种情况下,\.
被解释为 .
.
关于javascript - 使用 "new RegExp"和使用正斜杠符号创建正则表达式有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6149770/