什么是正則表達式?
正則表達式,又稱正規表示法、常規表示法(英語:Regular Expression,在代碼中常簡寫為regex、regexp或RE),計算機科學的一個概念。正則表達式使用單個字符串來描述、匹配一系列符合某個句法規則的字符串。在很多文本編輯器里,正則表達式通常被用來檢索、替換那些符合某個模式的文本。
swift/233648.html">swift 至今并沒有在語言層面上支持正則表達式,可能在開發app時正則表達式使用的場景并不多。
封裝
在 Cocoa 中我們可以使用 NSRegularExpression 來做正則匹配,所以我們在 NSRegularExpression 的基礎上封裝一個 RegularExpHelper 配匹一個字符串是否符合某個正則表達式。
struct RegularExpHelper { let RegularExp: NSRegularExpression init(_ pattern: String) throws { try RegularExp = NSRegularExpression(pattern: pattern, options: .caseInsensitive) } func match(inpuut: String) -> Bool { let matches = RegularExp.matches(in: inpuut, options: [], range: NSMakeRange(0, inpuut.count)) return matches.count > 0 }}
自定義 =~
有了封裝好的 RegularExpHelper,我們就可以方便的自定義運算符了。
infix operator =~ : ATPrecedenceprecedencegroup ATPrecedence { associativity: none higherThan: AdditionPrecedence lowerThan: MultiplicationPrecedence}func =~ (input: String, RegularExp: String) -> Bool { do { return try RegularExpHelper(RegularExp).match(inpuut: input) } catch _ { return false }}
運算符定義
associativity 結合律
即多個同類的操作符順序出現時的計算順序
優先級
然后我們就可以使用了
if "[email protected]" =~ "^([a-z0-9_//.-]+)@([//da-z//.-]+)//.([a-z//.]{2,6})$" { print("符合郵箱規則") } else { print("不符合郵箱規則") }
注意
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答