PySwiftyRegex
以 Pythonic 风格轻松处理 Swift 中的 Regex。
这是简单的
import PySwiftyRegex
if let m = re.search("[Tt]his is (.*?)easy", "I think this is really easy!!!") {
m.group() // "this is really easy"
m.group(1) // "really "
}
查看 更多示例。
要求
- iOS 7.0+ / Mac OS X 10.9+
- Xcode 8.0+
< 对于 Swift 2.3,请使用版本 0.3.0。
安装
内嵌框架需要iOS 8或OS X Mavericks或更高版本的最低部署目标。
要在针对iOS 7的项目中使用
PySwiftyRegex
,请考虑使用 CocoaSeeds 或将 PySwiftyRegex.swift 文件复制到您的项目中。
CocoaPods(iOS 8+, OS X 10.9+)
您可以使用 Cocoapods 来安装 PySwiftyRegex
,只需将其添加到您的 Podfile
。
platform :ios, '8.0'
use_frameworks!
target 'MyApp' do
pod 'PySwiftyRegex', '~> 1.0.0'
end
然后,运行以下命令
$ pod install
Carthage(iOS 8+, OS X 10.9+)
将以下行添加到您的 Cartfile
或 Cartfile.private
github "cezheng/PySwiftyRegex" ~> 1.0.0
运行以下命令
$ carthage update
然后将由 Carthage 生成的 PySwiftyRegex.framework
拖到目标的 General
-> Embedded Binaries
。
CocoaSeeds (for iOS 7)
CocoaSeeds 允许您在 iOS 7 项目中使用 Swift 库。
创建 Seedfile
target :MyApp do
github 'cezheng/PySwiftyRegex', '1.0.0', :files => 'PySwiftyRegex/PySwiftyRegex.swift'
end
然后运行以下命令
$ seed install
现在您可以在您的 Xcode 项目中看到 PySwiftyRegex.swift 文件。构建并享用吧!
支持的正则表达式方法
如果您熟悉 Python 的 re 模块,您就可以开始了。如果不熟悉,您可以点击以下项目了解 Python 的 re 模块为何比 NSRegularExpression 的 API 繁琐。
re
re.RegexObject
re.MatchObject
更多使用示例
编译 RegexObject 以供未来重用
let regex = re.compile("this(.+)that")
从开始匹配模式
if let m = regex.match("this one is different from that") {
m.group() //"this one is different from that"
m.group(1) //" one is different from "
}
搜索模式(第一个匹配项)
if let m = regex.search("I want this one, not that one") {
m.group() //"this one, not that one"
m.group(1) //" one, not "
}
查找所有模式出现的实例
regex.findall("this or that, this and that") // ["this or that", "this and that"]
获取所有模式出现的匹配结果
for m in regex.finditer("this or that, this and that") {
m.group() // 1st time: "this or that", 2nd time: "this and that"
m.group(1) // 1st time: " or ", 2nd time: " and "
}
用模式分割字符串
let regex = re.compile("[\\+\\-\\*/]")
// By default, will split at all occurrences of the pattern
regex.split("1+2-3*4/5") // ["1", "2", "3", "4", "5"]
// Setting a maxsplit = 2
regex.split("1+2-3*4/5", 2) // ["1", "2", "3*4/5"]
替换模式
let regex = re.compile("[Yy]ou")
// Replacing all occurrences (2 times in this example)
regex.sub("u", "You guys go grap your food") // "u guys go grap ur food"
regex.subn("u", "You guys go grap your food") // ("u guys go grap ur food", 2)
// Setting maximum replace count = 1 (1 times in this example)
regex.sub("u", "You guys go grap your food", 1) // "u guys go grap your food"
regex.subn("u", "You guys go grap your food", 1) // ("u guys go grap your food", 1)
许可
PySwiftyRegex
是在MIT许可下发布的。有关详细信息,请参阅LICENSE。