RegEx help-快速路由网址

Jac*_*Guy 3 regex routes node.js express

我从其他Stack Overflow帖子中读到,您可以使用正则表达式来路由各种URL.我之前从未真正使用过RegExps,所以我需要一些帮助.如何路由以/ lobby /后跟十位数字开头的所有网址?像这样

app.get("/lobby/0000000000", function (req, res) ...
Run Code Online (Sandbox Code Playgroud)

谢谢.

hex*_*ide 9

这是一个有效的例子:

app.get(/^\/lobby\/[0-9]{10}$/, function(req, res) {
  // route handler here
});
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用参数检查:

app.param(function(name, fn){
  if (fn instanceof RegExp) {
    return function(req, res, next, val){
      var captures;
      if (captures = fn.exec(String(val))) {
        req.params[name] = captures;
        next();
      } else {
        next('route');
      }
    }
  }
});

app.param('id', /^[0-9]{10}$/);
app.get('/lobby/:id', function(req, res){
  res.send('user ' + req.params.id);
});
Run Code Online (Sandbox Code Playgroud)


end*_*cat 5

app.get('/lobby/:id', function(req, res){
    console.log( req.params.id );
    res.end();
});
Run Code Online (Sandbox Code Playgroud)

要么

app.get('/lobby/((\\d+))', function(req, res){
    console.log( req.params[0] );
    res.end();
});
Run Code Online (Sandbox Code Playgroud)

或者如果URL需要正好是10位数:

app.get('/lobby/((\\d+){10})', function(req, res){
    console.log( req.params[0] );
    res.end();
});
Run Code Online (Sandbox Code Playgroud)