PathTemplate

Build Status codecov

PathTemplate 的 Swift 实现,用于处理模板化的路径。灵感来源于 path-to-regexpURITemplate.swift

安装

Swift Package Manager

将以下内容添加到您的 Package.swift 文件的 dependencies: []

.package(url: "https://github.com/gjeck/PathTemplate.swift.git")

Cocoapods

将以下内容添加到您的 Podfile 文件中

pod 'PathTemplate'

基本用法

PathTemplate 对于处理结构化的 String 数据(例如 URL)非常有用。

展开路径模板
let template: PathTemplate = "/user/:id"
template.expand(["id": 123])
=> "/user/123"
确定模板中的参数
let template: PathTemplate = "https://api.github.com/repos/:owner/:repo/"
template.parameterNames
=> ["owner", "repo"]
提取给定路径中使用的参数
let template: PathTemplate = "/artist/:artistId/album/:albumId"
template.extract("/artist/123/album/456")
=> ["artistId": "123", "albumId": "456"]

参数修饰符

命名参数通过在单词字符 [A-Za-z0-9_] 的段前加上冒号来定义,例如 :user。可以添加额外的修饰符以表示不同的含义

  1. ? 参数是可选的
  2. * 零个或多个段
  3. + 一个或多个段
? 可选
let template: PathTemplate = "https://:hostname/:path?"
template.expand(["hostname": "github.com"])
=> "https://github.com"

template.expand(["hostname": "github.com", "path": "user"])
=> "https://github.com/user"
* 零个或多个
let template: PathTemplate = "https://:hostname/:path*"
template.expand(["hostname": "github.com", "path": ["user", "gjeck"]])
=> "https://github.com/user/gjeck"

template.expand(["hostname": "github.com"])
=> "https://github.com"
+ 一个或多个
let template: PathTemplate = "https://:hostname/:path+"
template.expand(["hostname": "github.com", "path": ["user", "gjeck"]])
=> "https://github.com/user/gjeck"

template.expand(["hostname": "github.com"])
=> nil

正则表达式参数

可以为参数提供自定义正则表达式,以覆盖默认匹配。例如,您可以强制匹配路径中的数字。

let template: PathTemplate = "/image-:imageId(\\d+).png"
template.expand(["imageId": 123])
=> "/image-123.png"

template.expand(["imageId": "abc"])
=> nil

未命名参数

可以编写一个仅包含匹配组的未命名参数。它的工作方式与命名参数相同,只不过它将被数字索引。

let template: PathTemplate = "/cool/(\\d+)/(.*)"
template.parameterNames
=> ["0", "1"]

template.expand(["0": 123, "1": "wow"])
=> "/cool/123/wow"

高级用法

强制区分大小写匹配

let template = PathTemplate("/User/:id", options: .init(isCaseSensitive: true))
template.extract("/user/123") // Note that "user" has a lowercase "u"
=> [] 

访问底层的路径正则表达式

let template: PathTemplate = "/user/:id"
template.regex
=> <NSRegularExpression: 0x102745860> ^\/user\/([^\/]+?)(?:\/)?$