【发布时间】:2013-03-09 21:27:28
【问题描述】:
我正在查看express.js 源代码,以了解它如何将命名路由参数映射到req.params 属性。
对于那些不知道的人,在 express.js 中你可以定义带有命名参数的路由,使它们成为可选的,只允许具有特定格式(以及更多)的路由:
app.get("/user/:id/:name?/:age(\\d+)", function (req, res) {
console.log("ID is", req.params.id);
console.log("Name is", req.params.name || "not specified!");
console.log("Age is", req.params.age);
});
我意识到这个功能的核心是在lib/utils.js 中定义的一个名为pathRegexp() 的方法。方法定义如下:
function pathRegexp(path, keys, sensitive, strict) {
if (path instanceof RegExp) return path;
if (Array.isArray(path)) path = '(' + path.join('|') + ')';
path = path
.concat(strict ? '' : '/?')
.replace(/\/\(/g, '(?:/')
.replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function (_, slash, format, key, capture, optional, star) {
keys.push({ name: key, optional: !! optional });
slash = slash || '';
return ''
+ (optional ? '' : slash)
+ '(?:'
+ (optional ? slash : '')
+ (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'
+ (optional || '')
+ (star ? '(/*)?' : '');
})
.replace(/([\/.])/g, '\\$1')
.replace(/\*/g, '(.*)');
return new RegExp('^' + path + '$', sensitive ? '' : 'i');
}
重要的部分是第 7 行的正则表达式,/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g,它以这种方式对路径名的匹配部分进行分组:
斜线
格式
我不知道这个的目的是什么,需要解释。 键
这个词(即 捕获
写在 可选
星号
回调处理程序从上面的组构建一个正则表达式。 现在的问题是,这里 我的理解是根据下面这行: 提到的正则表达式是, 如果您在 那么有什么意义呢? 我问这个,因为:/ 符号
\w+):符号 kbd> key 前面的正则表达式。应该用括号括起来(例如(.\\d+))? 987654335 @ kbd> * 符号
format的目的是什么?(format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)'))
slash 组之后放置. 符号并且未指定匹配条件(正则表达式包裹在key 之后的括号中),则生成的正则表达式匹配path 的其余部分,直到它获取. 或/ 符号。
【问题讨论】:
标签: express.js javascript regex node.js express