Regex - Why doesn't this pattern work when using the new RegExp method?

一世执手 提交于 2021-01-29 15:52:31

问题


I'm searching this string for an the 'invite=XXXX' part. I am using a capturing group to extract the value between '=' and ';'. When I use the first regex method it works, but when I use the second it doesn't. Why is this?

var string = "path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; invite=1323969929057; path=/; expires=Sat, 14 Jan 2012 17:25:29 GMT;";

// first method
var regex1 = /invite=(\w+)/;
var regexMatch1 = string.match(regex1);

// second method
var regex2 = new RegExp("/invite=(\w+)/");  
var regexMatch2 = string.match(regex2);

// log results
console.log(regexMatch1);
console.log(regexMatch2);

Working example here >>


回答1:


You have to escape the \ and like Jake said, remove the slashes.

var regex2 = new RegExp("invite=(\\w+)");  
                                  ^ Notice 2 "\"

http://jsfiddle.net/ZqkQ9/10/




回答2:


When you use the RegExp() constructor, the slashes are not needed. Change to this:

var regex2 = new RegExp("invite=(\\w+)"); 



回答3:


Because the / is for a regex literal. Since you are using the RegExp object, you need to remove the slashes. You also need to escape the backslash since you aren't using a literal:

var regex2 = new RegExp("invite=(\\w+)");  
var regexMatch2 = string.match(regex2);



回答4:


It should be:

 var regex2 = new RegExp("invite=(\\w+)");  

Regular expressions in string form have no / prefix and postfix and all escape characters must have \\ instead of \.




回答5:


You don't need the slashes while creating RegExp object using RegExp.

If you want, you can even compare the patterns using RegExp.source

Try console.log(regex1.source === regex2.source)

Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp




回答6:


remove the /'s from the RegExp constructor, scape the \w and put the second parameter:

var regex2 = new RegExp("invite=(\\w+)", "");  


来源:https://stackoverflow.com/questions/8524440/regex-why-doesnt-this-pattern-work-when-using-the-new-regexp-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!