【问题标题】:What is the proper regex syntax to use with express routes?与快速路由一起使用的正确正则表达式语法是什么?
【发布时间】:2015-08-26 04:30:04
【问题描述】:

我正在使用正则表达式进行快速路由,但遇到了障碍。当以结果结尾的 url 是 GET 时,我会运行一堆测试。对字符串不以结尾的 GET 结果返回文件夹列表和测试链接。

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

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

但我终其一生都无法弄清楚如何在 express 中实现这些。我目前有:

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 和路径 req 参数位于 req.params 对象中。

例如,以下三行在字符串时有效,但在 url 传递给 express 时无效:

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

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

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

【问题讨论】:

    标签: javascript regex node.js express


    【解决方案1】:

    显然语法是纯正则表达式。谁会知道!我目前正在使用:

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

    它就像一个魅力。仍然没有弄清楚如何在那里获取变量。但它现在有效。

    【讨论】:

      猜你喜欢
      • 2019-02-24
      • 2016-01-15
      • 2018-08-29
      • 2013-10-22
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多