Path-to-RegExp将路径字符串转换为正则表达式的工具

联合创作 · 2023-09-30 13:45

Path-to-RegExp 是一个可以将诸如/user/:name这样的路径字符串转换为正则表达式的工具。

安装

npm install path-to-regexp --save 

用法

const { pathToRegexp, match, parse, compile } = require("path-to-regexp");

// pathToRegexp(path, keys?, options?)
// match(path)
// parse(path)
// compile(path)

Path to regexp

pathToRegexp函数将根据提供的path参数返回一个正则表达式对象。它接受以下参数:

  • Path 字符串、字符串数组或正则表达式。
  • Keys (可选)要填充路径中找到的键的数组。
  • Option (可选)
    • sensitive 
    • strict 
    • end
    • start
    • delimiter 
    • EndsWith
    • encode
    • prefixes
const keys = [];
const regexp = pathToRegexp("/foo/:bar", keys);
// regexp = /^\/foo(?:\/([^\/#\?]+?))[\/#\?]?$/i
// keys = [{ name: 'bar', prefix: '/', suffix: '', pattern: '[^\\/#\\?]+?', modifier: '' }]

参数

path 参数用于定义参数和填充键。

命名参数

命名参数是通过在参数名称前加一个冒号来定义的( :foo)

const regexp = pathToRegexp("/:foo/:bar");
// keys = [{ name: 'foo', prefix: '/', ... }, { name: 'bar', prefix: '/', ... }]

regexp.exec("/test/route");
//=> [ '/test/route', 'test', 'route', index: 0, input: '/test/route', groups: undefined ]

请注意:参数名称必须使用“单词字符”( [A-Za-z0-9_])。

自定义匹配参数

参数可以有一个自定义的正则表达式,它会覆盖默认匹配 ( [^/]+)。例如,可以匹配路径中的数字或名称:

const regexpNumbers = pathToRegexp("/icon-:foo(\\d+).png");
// keys = [{ name: 'foo', ... }]

regexpNumbers.exec("/icon-123.png");
//=> ['/icon-123.png', '123']

regexpNumbers.exec("/icon-abc.png");
//=> null

const regexpWord = pathToRegexp("/(user|u)");
// keys = [{ name: 0, ... }]

regexpWord.exec("/u");
//=> ['/u', 'u']

regexpWord.exec("/users");
//=> null

提示:反斜杠需要在 JavaScript 字符串中使用另一个反斜杠进行转义。

自定义前缀和后缀

可以将参数包裹起来,{}为你的细分创建自定义前缀或后缀:

const regexp = pathToRegexp("/:attr1?{-:attr2}?{-:attr3}?");

regexp.exec("/test");
// => ['/test', 'test', undefined, undefined]

regexp.exec("/test-test");
// => ['/test', 'test', 'test', undefined]
浏览 6
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报