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.utf8.count))
return matches.count > 0
}
}
func checkEmail() -> Bool{
let mailPattern = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
guard let matcher = try? RegexHelper(mailPattern) else {
return false
}
let maybeMainlAddress = "onev@onevcat.com"
if matcher.match(maybeMainlAddress) == true {
print("有效的邮箱地址")
return true
}
return false
}
// 定义优先级
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 "onev@onevcat.com" =~ "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$" {
print("有效的邮箱地址")
}
网友评论