node.js 用于 Express 中路由匹配的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10858005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:48:32  来源:igfitidea点击:

Regex for route matching in Express

regexnode.jsexpress

提问by Jonathan Ong

I'm not very good with regular expressions, so I want to make sure I'm doing this correctly. Let's say I have two very similar routes, /discussion/:slug/and /page/:slug/. I want to create a route that matches both these pages.

我不太擅长正则表达式,所以我想确保我正确地做到了这一点。假设我有两条非常相似的路线,/discussion/:slug/并且/page/:slug/. 我想创建一个匹配这两个页面的路线。

app.get('/[discussion|page]/:slug', function(req, res, next) {
  ...enter code here...
})

Is this the correct way to do it? Right now I'm just creating two separate routes.

这是正确的方法吗?现在我只是在创建两条独​​立的路线。

someFunction = function(req, res, next) {..}
app.get('/discussion/:slug', someFunction)
app.get('/page/:slug', someFunction)

回答by Jonathan Ong

app.get('/:type(discussion|page)/:id', ...)works

app.get('/:type(discussion|page)/:id', ...)作品

回答by Peter Lyons

You should use a literal javascript regular expression object, not a string, and @sarnold is correct that you want parens for alternation. Square brackets are for character classes.

您应该使用文字 javascript 正则表达式对象,而不是字符串,@sarnold 是正确的,您希望使用括号进行交替。方括号用于字符类。

const express = require("express");
const app = express.createServer();
app.get(/^\/(discussion|page)\/(.+)/, function (req, res, next) {
  res.write(req.params[0]); //This has "discussion" or "page"
  res.write(req.params[1]); //This has the slug
  res.end();
});

app.listen(9060);

The (.+)means a slug of at least 1 character must be present or this route will not match. Use (.*)if you want it to match an empty slug as well.

(.+)意味着必须存在至少 1 个字符的 slug,否则此路由将不匹配。(.*)如果您希望它也与空弹头相匹配,请使用。