struct RegexHelper { let regex: NSRegularExpression? init(_ pattern: String) { var error: NSError? regex = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: &error) } func match(input: String) -> Bool { if let matches = regex?.matchesInString(input, options: nil, range: NSMakeRange(0, count(input))) { return matches.count > 0 } else { return false } } } //验证方式 let mailPattern = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$" let matcher = RegexHelper(mailPattern) let maybeMailAddress = "[email protected]" if matcher.match(maybeMailAddress) { println("有效的邮箱地址") } else { println("无效的邮箱地址") }
时间: 2024-11-08 22:44:16