SwiftVerbalExpressions 是一个Swift库,可以通过函数的方式实现复杂的正则表达式功能。从JavaScript的版本JSVerbalExpressions移植。
这里有几个简单的例子来了解VerbalExpressions的工作原理:
检查网址是否有效
// Create an example of how to test for correctly formed URLs
let tester = VerEx()
.startOfLine()
.then("http")
.maybe("s")
.then("://")
.maybe("www")
.anythingBut(" ")
.endOfLine()
// Create an example URL
let testMe = "https://www.google.com"
// Use test() method
if tester.test(testMe) {
println("We have a correct URL") // This output will fire
}
else {
println("The URL is incorrect")
}
// Use =~ operator
if testMe =~ tester {
println("We have a correct URL") // This output will fire
}
else {
println("The URL is incorrect")
}
println(tester) // Outputs the actual expression used: "^(?:http)(?:s)?(?::\/\/)(?:www)?(?:[^ ]*)$"
替换字符串
let replaceMe = "Replace bird with a duck"
// Create an expression that seeks for word "bird"
let verEx = VerEx().find("bird")
// Execute the expression like a normal RegExp object
let result = verEx.replace(replaceMe, with: "duck")
println(result) // Outputs "Replace duck with a duck"
替换字符串简写方式
let result2 = VerEx().find("red").replace("We have a red house", with: "blue")
println(result2) // Outputs "We have a blue house"
API文档
可以查看JavaScript版本的API文档。