简体   繁体   中英

Matching a string with a regex gives null even though it should match

I am trying to get my regex to work in JavaScript, but I have a problem.

Code :

var reg = new RegExp('978\d{10}');
var isbn = '9788740013498';
var res = isbn.match(reg);

console.log(res);

However, res is always null in the console.

This is quite interesting, as the regex should work.

My question: then, what is the right syntax to match a string and a regex?

(If it matters and could have any say in the environment: this code is taken from an app.get view made in Express.js in my Node.js application)

Because you're using a string to build your regex, you need to escape the \\ . It's currently working to escape the d , which doesn't need escaping.

You can see what happens if you create your regex on the chrome console:

new RegExp('978\d{10}');
// => /978d{10}/

Note that there is no \\d , only a d , so your regex matches 978dddddddddd . That is, the literal 'd' character repeated 10 times.

You need to use \\\\ to insert a literal \\ in the string you're building the regex from:

var reg = new RegExp('978\\d{10}'); 
var isbn = '9788740013498';
var res = isbn.match(reg);

console.log(res)

// => ["9788740013498", index: 0, input: "9788740013498"] 

You need to escape with double back slash if you use RegExp constructor:

var reg = new RegExp('978\\d{10}');

Quote from documentation :

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