I am trying to build a regex that will match any combination of numerals (0-9), alpha characters and hyphens, but not purely numeric, for use in routing. The simplest example I can give is the following..
router.param('slug', function(req, res, next, slug){
req.slug = slug;
next();
}
router.get(':slug((?=[a-zA-Z-])[a-zA-Z-\d]+)', function(req, res){
res.send(req.slug);
}
The logic behind the regex has been tested at regex101.com
(?=[a-zA-Z-])[a-zA-Z-\\d]+
The idea is a positive lookahead to match at least one of az, AZ or -, and then a match for az,AZ,0-9 in any combination.
Except it doesn't work in express. It will match "h", "h-", "h-9", but not with "9-" or "9a". Furthermore, the slug argument in the param call is empty when it does match. I am stumped. I suspect it might be some escaping issue with the regex string?
Here is a reference to the docs for the param call. http://expressjs.com/en/api.html#router.param
Any help appreciated.
Update: I think it has something to do with there being no capture group in the regex..
Another update: the following regex has a capture group, works at regex101.com, but no dice with express...what am I missing here?
(\\d*[a-zA-Z-][a-zA-Z-\\d]*$)+
Third update: express is calling this library https://github.com/pillarjs/path-to-regexp , which helpfully points out I should be escaping backslashes. I have edited the post to reflect this. The library itself is turning this
(\\d*[a-zA-Z-][a-zA-Z-\\d]*$)+
into this..
^\/(?:((\d(.*)[a-zA-Z-][a-zA-Z-\d](.*)$))+)\/?$
Thanks
This should do it:
(?!\\d+$)[a-zA-Z-\\d]+
Matches:
foo-123
123-bar
foobar
Does not match:
123456
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.