Swift 正则表达式
2020-09-11 本文已影响0人
gaookey
struct RegexHelper {
let regex: NSRegularExpression
init(_ pattern: String) throws {
try regex = NSRegularExpression(pattern: pattern,
options: .caseInsensitive)
}
func match(_ input: String) -> Bool {
let matches = regex.matches(in: input,
options: [],
range: NSMakeRange(0, input.utf16.count))
return matches.count > 0
}
}
let mailPattern = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
do {
let matcher = try RegexHelper(mailPattern)
let maybeMailAddress = "123@163.com"
if matcher.match(maybeMailAddress) {
print("有效的邮箱地址")
}
} catch { }
自定义符号正则匹配
precedencegroup MatchPrecedence {
associativity: none
higherThan: DefaultPrecedence
}
infix operator =~: MatchPrecedence
func =~(lhs: String, rhs: String) -> Bool {
do {
return try RegexHelper(rhs).match(lhs)
} catch _ {
return false
}
}
if "123@163.com" =~ "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$" {
print("有效的邮箱地址")
}
摘录来自: 王巍 (onevcat). “Swifter - Swift 必备 Tips (第四版)。”