简体   繁体   English

节点Express 4-用于路由的正则表达式。 字母或字母数字,包括连字符,但非纯数字

[英]Node, Express 4 - Regex for routing. Alpha or Alphanumeric including hyphen but not purely numeric

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. 我正在尝试构建一个正则表达式,以匹配数字(0-9),字母字符和连字符的任意组合,而不是纯数字,用于路由。 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 regex背后的逻辑已在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. 这个想法是一个积极的前瞻,可以匹配az,AZ或-中的至少一个,然后匹配az,AZ,0-9的任意组合。

Except it doesn't work in express. 除非它不适用于快递。 It will match "h", "h-", "h-9", but not with "9-" or "9a". 它将匹配“ h”,“ h-”,“ h-9”,但不匹配“ 9-”或“ 9a”。 Furthermore, the slug argument in the param call is empty when it does match. 此外,当参数匹配时,param调用中的slug参数为空。 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. 这里是对param调用文档的参考。 http://expressjs.com/en/api.html#router.param 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? 另一个更新:以下正则表达式有一个捕获组,可在regex101.com上运行,但没有带有Express的骰子...我在这里缺少什么?

(\\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. 第三次更新:express正在调用该库https://github.com/pillarjs/path-to-regexp ,它有帮助地指出我应该转义反斜杠。 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 foo-123 123-bar foobar

Does not match: 不匹配:

123456

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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