18

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");
  }

我得到了两个不一致的结果:

电子邮件匹配的正则表达式1
电子邮件不匹配的正则表达式2

我想知道这里是否有任何区别,或者我在这个特定示例中省略了某些内容?
有关可执行示例,请参阅此处

4

4 回答 4

14
于 2011-05-27T08:44:52.603 回答
13

/.../ is called a regular expression literal. new RegExp uses the RegExp constructor function and creates a Regular Expression Object.

From Mozilla's developer pages

Regular expression literals provide compilation of the regular expression when the script is evaluated. When the regular expression will remain constant, use this for better performance.

Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

于 2011-05-27T08:47:57.733 回答
4

这将对您有所帮助 http://www.regular-expressions.info/javascript.html 请参阅“如何使用 JavaScript RegExp 对象”部分

如果您使用 RegExp(regx) regx 应该是字符串格式 ex:- \w+ 可以创建为regx = /\w+/或 as regx = new RegExp("\\w+")

于 2011-05-27T08:44:33.493 回答
2

Difference is in escaping at least in your case. When you use / / notation, you have to escape '/' with '\/', when you're using Regexp notation you escape quotes

于 2011-05-27T08:46:06.500 回答