简体   繁体   中英

Not able to escape “?” but “\” works fine in javascript regex

I have following example (in node):

var reg = new RegExp("aa\?b", 'g');
var msgg = "aa?b"

if(msgg.match(reg)){
    console.log(1);
} else {
    console.log(0);
}

This prints 0 or returns null. I don't understand why it works if ? is replaced with \\ but not in case of ?. Is ? some more special than any others??

You need to double escape, like this:

var reg = new RegExp("aa\\?b", 'g');

Or use RegExp literal:

 var reg = /aa\?b/g;

Reason is that JavaScript string "\\?" evaluates to "?" because ? is not a special escape character. Hence your RegExp receives a literal question mark and not an escaped one. Double escaping ensures the "\\" is treated literally.

Passing the literal notation instead of the string notation to the constructor your regexp works:

 var reg = new RegExp(/aa\\?b/, 'g'); var msgg = "aa?b" console.log(msgg.match(reg)) 

From MDN :

There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:

/ab+c/i;
new RegExp('ab+c', 'i');
new RegExp(/ab+c/, 'i');

The literal notation provides a compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

The constructor of the regular expression object, for example, new RegExp('ab+c') , 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.

Starting with ECMAScript 6, new RegExp(/ab+c/, 'i') no longer throws a TypeError ("can't supply flags when constructing one RegExp from another") when the first argument is a RegExp and the second flags argument is present. A new RegExp from the arguments is created instead.

When using the constructor function, the normal string escape rules (preceding special characters with \\ when included in a string) are necessary. For example, the following are equivalent:

var re = /\w+/;
var re = new RegExp('\\w+');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM