AppDeveloperKit-String
Swift String 工具
概述
AppDeveloperKit-String 是一个 Swift String 库,提供对索引和正则表达式匹配及替换的支持。
- 获灵启发的匹配和替换
- 字符串扩展的实现
- 支持 `=~` 操作符
- 使用 Regex 包装类的可选备用接口
- 支持 Unicode 字符,包括 ZWJ 序列以组合元素
👩🚀
- 灵活的匹配
- 支持全局和大小写不敏感标志
- 模板支持
- 匹配输出为捕获组或布尔结果
- 捕获组可以作为元组或数组返回
- 在闭包中提供预处理、匹配和后处理
- 通过索引、范围和闭包索引进行索引
- 为接口提供了全面的单元测试
通过 Cocoapods 安装
将以下任一选项添加到您的 Podfile
推荐:安装 AppDeveloperKit-String 的所有组件
pod 'AppDeveloperKit-String'
最小安装
如果模块与Regex包装类发生冲突,您可以选择只添加对 =~ 操作符的匹配和替换支持,以及下标支持。
pod 'AppDeveloperKit-String/String'
pod 'AppDeveloperKit-String/Subscript'
依赖关系
通过在Podfile中添加 use_frameworks!
,使用框架整合依赖关系。然后运行 pod install
。
文档
请参阅 Documentation.playground,以获得AppDeveloperKit-String的完整规范,后者作为一个Swift playground呈现。
匹配示例
捕获组以元组形式返回。闭包提供预匹配、匹配和后匹配。
var (d1,d2) = "A56B" =~ (.M,"(\\d)(\\d)", { (preMatch, match, postMatch) in
preMatch // A
match // 56
postMatch // B
})
// ("5","6")
如果您只需要捕获组,则可以简化为:
var (d1,d2) = "A56B" =~ (.M,"(\\d)(\\d)")
以数组形式返回相同的捕获组
var arr: [String] = "A56B" =~ (.M,"(\\d)(\\d)")
数组可以是可选的(nil 表示未匹配)。
var arr: [String]? = "A56B" =~ (.M,"(\\d)(\\d)")
元组或数组结果,带或不带闭包,也支持全局 "g" 标志和/或大小写不敏感 "i" 标志。标志参数位于模式之后(在可选闭包之前)。
var arr: [String] = "4XY5" =~ (.M,"([a-z])", "gi", { (preMatch, match, postMatch) in
preMatch // 4
match // Y
postMatch // 5
})
// ["X","Y"]
使用Regex类的另一个接口(也适用于元组和布尔结果)
var arr: [String] = Regex.m(str: "4XY5", pattern: "([a-z])", flags: "ig", completion: { (preMatch, match, postMatch) in
preMatch
match
postMatch
})
布尔结果表示匹配
var result1: Bool = "XY" =~ (.M,"\\d") // false
// With flags argument
var result2: Bool = "XY" =~ (.M,"[a-z]", "i") // true
替换示例
使用模板中的模式和新值进行原地替换。返回替换的次数。
var str = "XY"
let count = str =~ (.S,"(\\w)(\\w)","$2$1") // 1 str = YX
// With flags argument
str = "XY ZW"
let count = str =~ (.S, "(\\w)(\\w)","$2$1", "g") // 2 str = YX WZ
使用Regex类的另一个接口
str = "XY"
let count = Regex.s(str: &str, pattern: "([a-z])([a-z])", replacement: "$2$1", flags: "i") // 1 str = YX
下标示例
通过索引、范围和ClosedRange来进行下标。支持Unicode。
str = "A😎B👩🚀CDE"
str[1] // 😎
str[2] // B
str[3] // 👩🚀
str[1..<4] // 😎B👩🚀
str[1...4] // 😎B👩🚀C