swift 正则表达式运用实例(选自《swifter 100个swift开发必备tip 》)

    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("无效的邮箱地址")
        
        }


你可能感兴趣的:(swift正则)