使用 CocoaPods。
添加到您的 Podfile
pod 'Regex'
然后从 shell 中运行 pod install
$ pod install
String.grep()
此方法模仿 JavaScript 的 String.match()
方法。它返回一个 Regex.MatchResult
对象。对象的 captures
属性是一个 String
数组,与它的 JavaScript 等效物类似。
let result = "Winnie the Pooh".grep("\\s+([a-z]+)\\s+")
result.searchString == "Winnie the Pooh"
result.captures.count == 2
result.captures[0] == " the "
result.captures[1] == "the"
result.boolValue == true // `boolValue` is `true` if there were more than 0 matches
// You can use `grep()` in conditionals because of the `boolValue` property its result exposes
let emailAddress = "bryn&typos.org"
if !emailAddress.grep("@") {
// that's not an email address!
}
String.replaceRegex()
此方法模仿接受正则表达式参数的 JavaScript 的 String.replace()
方法。
let name = "Winnie the Pooh"
let darkName = name.replaceRegex("Winnie the ([a-zA-Z]+)", with: "Darth $1")
// darkName == "Darth Pooh"
运算符 =~
您可以使用 =~
运算符在 String
(左操作数)中搜索正则表达式(右操作数)。它与调用 theString.grep("the regex pattern")
相同,但在某些情况下可能更清晰。它返回与 String.grep()
相同的 Regex.MatchResult
对象。
"Winnie the Pooh" =~ Regex("\\s+(the)\\s+") // returns a Regex.MatchResult
快速遍历 Regex 的捕获
for capture in ("Winnie the Pooh" =~ Regex("\\s+(the)\\s+")).captures {
// capture is a String
}
map()
函数用于替换通过覆盖 map()
函数,可以使用一种更“函数式编程”的方法来进行字符串替换。为了与整体目标保持一致,即重用完美的轮子(即,NSRegularExpression
),此函数仅调用 NSRegularExpression.replaceMatchesInString()
。
func map (regexResult:Regex.MatchResult, replacementTemplate:String) -> String
您可以这样使用它
let stageName = map("Winnie the Pooh" =~ Regex("([a-zA-Z]+)\\s+(the)(.*)"), "$2 $1")
// stageName == "the Winnie"
或者如果您有一些函数式运算符(例如:https://github.com/brynbellomy/Funky),则稍微简洁一些
("Winnie the Pooh" =~ Regex("([a-zA-Z]+)\\s+(the)(.*)")) |> map‡("$2 $1")
……但是您必须像我一样疯狂,才能觉得这比 "Winnie".replaceRegex(_:withString:)
更易读,所以请随意。