Reputation: 3832
I'm trying to find some documentation about regex in Express, but the information in Express API is very sparse. I'm trying to do a regex matching objectID. This example about regex is given in the Express documentation.
router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function(req, res){ ... });
I have tried the following in my router, and it seems to work fine.
client.get('/staff/:id([0-9a-fA-F]{24})', function(req, res) { ... });
But there are some differences that i can't figure out...
'
, the example in the API is not. What
does this mean? Is my expression a string and not a regex?/^
or ?$/
. Not knowing much about
regex I guess this is some kind of anchors. Do i need this? \
the first part of my URL /staff/:id
. Is this something i
should do?Also, does anyone know about a extensive resource for reading about regex in Express routers... or parameter options or whatever it is I'm doing above...
Upvotes: 1
Views: 498
Reputation: 14581
It is worth reading the source code for the route matching, but here is the short form.
'abc'
is a JS string; /abc/
is a JS regex. The string can be used to create a regex, which is what you are doing. So both are valid. To see the difference, try doing var re = /abc/
and var re = new RegExp('abc')
^
is a starting anchor while $
is an ending anchor. ^abc
will match "abc", "abcde" but not "zabcd" because it needs to start with "abc". abc$
will match "abc", "zabc" but not "abcd", because it needs to end with "abc"./
and ending with /
, if you want to use slashes in your RegExp, you need to escape them, else how will the interpreter know that this is a slash character and not the end of your RegExp? If you are using a string, it knows it is not, and so you do not need to escape.For the last, try this:
"abc".match(/abc/); // works
"abc".match('/abc/'); // fails because there are no slashes
"/abc/".match('/abc/'); // works
"/abc/".match(/abc/); // works because "abc" is in there
Of course, you can escape the slashes, if you so choose
"/abc/".match('\/abc\/'); // works
"abc".match('\/abc\/'); // fails
Upvotes: 1