Swift Expression 是一个用 Swift 构建的正则表达式框架,旨在简化 NSRegularExpression 的使用。该框架提供了低开销的模式匹配。
Swift 或 Objective-C 中没有像 JavaScript 或 Ruby 等其他语言那样的原生正则表达式实现。这个框架的目标是以一种“Swift 化”的方式简化正则表达式的使用。该框架构建于 NSRegularExpression 之上,只提供了易于调用的方法和易于操作的对象。为了尽可能地接近原生体验,Swift 的 String
类型已经扩展了新的正则表达式方法。
Xcode 10.2
Swift 4.2
iOS 8.0+
Regex 可以通过多种方式创建。
if let regex = Regex("^\\d") {
// use regex object
}
前缀运算符用于初始化一个 regex 结构体,并且是构建在可失败的初始化器之上的。
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
来安装它
platform :ios, '8.0'
use_frameworks!
target 'MyApp' do
pod 'SwiftExpression'
end
您可以使用 Carthage 将 SwiftExpression
添加到您的 Cartfile
来安装它
github "lostatseajoshua/SwiftExpression"
import PackageDescription
let package = Package(
name: "YourProject",
targets: [],
dependencies: [
.Package(url: "https://github.com/lostatseajoshua/SwiftExpression.git",
majorVersion: 2),
]
)
要手动在您的项目中使用此库,请执行以下操作。
通过从 releases 下载框架,将 SwiftExpression.framework 添加到您的项目
查看这个用 SwiftExpression 构建的演示项目。它使用正则表达式模式高亮显示 UITextView 中的文本,该模式输入到 UITextField 中!
Joshua Alvarado - Twitter - Website
此项目根据 MIT 许可证 发布。