SwiftExpression
Swift Expression 是一个用 Swift 构建的 Regex 框架,以使其更容易处理 NSRegularExpression。此框架提供了低开销以处理模式匹配。
动机
Swift 或 Objective-C 中没有原生的 Regex 实现,就像其他语言(如 JavaScript 或 Ruby)中那样。此框架的目标是使以 "Swifty" 方式处理 Regex 更容易。该框架基于 NSRegularExpression 构建,只需调用简单的方法和易于处理的简单对象。为了尽可能地感觉像本地实现,Swift 的 String
类型已扩展用于 Regex 的新方法。
要求
Xcode 10.2
Swift 4.2
iOS 8.0+
代码示例
创建一个正则表达式对象
正则表达式可以通过多种方式创建。
可失败初始化器
if let regex = Regex("^\\d") {
// use regex object
}
前缀运算符
前缀运算符用于初始化正则表达式结构体,并基于可失败初始化器构建。
if let regex = <>"^\\d" {
// use regex object
}
中缀运算符
使用自定义中缀运算符检查匹配。
let str = "333-aa-bb"
let regexPatternStr = "^\\d"
// string to search in on left hand side, regex pattern in string format on right hand side
if str ~= regexPatternStr {
// a match is in the string continue processing
} else {
// failed to find a single match in string
}
字符串扩展方法
匹配
let match = str.match(regex) // Returns a Regex.Match struct
match.components // Returns a collection of tuples that are the substring match and range of the match [(String, Range<String.Index>)]
match.subStrings() // Returns a collection of the substring matches [String]
match.ranges() // Returns a collection of ranges of the matches [Range<String.Index>]
替换
str.replace(regex, with: replaceStr) // Returns a new string with matches replaced with replacement string
查找
str.find(regex) // Returns true if a match exists in the string
安装
@available(iOS 8, *)
CocoaPods
您可以通过将 SwiftExpression
添加到您的 Podfile
中来使用 CocoaPods 安装它。
platform :ios, '8.0'
use_frameworks!
target 'MyApp' do
pod 'SwiftExpression'
end
Carthage
您可以通过将 SwiftExpression
添加到您的 Cartfile
中来使用 Carthage 安装它。
github "lostatseajoshua/SwiftExpression"
Swift Package Manager
import PackageDescription
let package = Package(
name: "YourProject",
targets: [],
dependencies: [
.Package(url: "https://github.com/lostatseajoshua/SwiftExpression.git",
majorVersion: 2),
]
)
Manually
在您的项目中手动使用此库,请按照以下步骤操作。
请从 releases 下载并将 SwiftExpression.framework 添加到您的项目中。
Demo
查看此使用 SwiftExpression 构建的项目示例。它使用输入到 UITextField 的正则表达式在 UITextView 中突出显示文本!
贡献者
Joshua Alvarado - Twitter - 网站
许可协议
本项目采用 MIT 许可协议 发布。