快速路由使用正确的正则表达式语法是什么? [英] What is the proper regex syntax to use with express routes?

查看:121
本文介绍了快速路由使用正确的正则表达式语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用正则表达式进行快速路由,但遇到了障碍.当结果为url的网址为GET时,我会进行大量测试.字符串未结尾结果上的GET返回文件夹列表和测试链接.

I'm using regex for express routing and I've hit a roadblock. I have a bunch of tests that get run when a url ending with result is GET. a GET on a string not ending in result returns a list of folders and links to tests.

我有一个适用于普通字符串的正则表达式

I have a regex that works on normal strings

var noresult = new RegExp(/^(?![\w\/:].*result$)/);
var result = new RegExp(/^[\w\/:].*result$/);

但是我无法终生想出如何快速实现这些目标.我目前有:

But I cannot for the life of me figure out how to implement these in express. I currently have:

router.get('/:testPath(^[\w\/:].*result$)', [function (req, res, next) {
    // run mocha test
    // render page
}

用于我的测试和

router.get('/:path(?![\w\/:].*result$)', function (req, res) {
    // build folder/file structure
    // render page
}

,但是这些都不适用于任何网址.我希望testPath和path req参数在req.params对象中.

but neither of these works for any url. I want the testPath and path req params to be in the req.params object.

例如,以下三行在使用字符串时有效,但在传递表达式时不起作用:

For example, the following three lines work when strings, but not when urls passed to express:

/test/path/to/test
/test/path/to/test/
/test/path/to/testfile/result

在快速路由示例中,我已经看到了同时使用和不使用/^或$/来开始或结束字符串的示例.我不确定它们是否属于那里.

I've seen examples that both use and do not use the /^ or $/ to begin or end the string in express routing examples. I'm not sure if they belong there or not.

在快递路线中实现正则表达式的正确方法是什么?

What is the proper way to implement regex in express routes?

推荐答案

显然,语法是纯正则表达式.谁知道呢!我当前正在使用:

Apparently the syntax is pure regex. Who would have known! I'm currently using:

router.get(/[\w\/:]*result$/, [function (req, res, next) {
router.get(/^(?![\w\/\:].*result$)/, function (req, res, next) {

,它就像一种魅力.仍未弄清楚如何在其中获取变量.但这暂时有效.

and it works like a charm. Still haven't figured out how to get variables in there. But it works for now.

这篇关于快速路由使用正确的正则表达式语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆