SwiftVerbalExpressions 是一個Swift庫,可以通過函數(shù)的方式實(shí)現(xiàn)復(fù)雜的正則表達(dá)式功能。從JavaScript的版本JSVerbalExpressions移植。
這里有幾個簡單的例子來了解VerbalExpressions的工作原理:
檢查網(wǎng)址是否有效
// 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文檔。