美文网首页
记录学习--正则表达式(swift)

记录学习--正则表达式(swift)

作者: 乂滥好人 | 来源:发表于2016-12-05 14:17 被阅读28次

    仅做学习使用,不做任何用途

    enum Validate {
        /** 邮箱 */
        case email(_: String)
        /** 手机号码 */
        case phoneNum(_: String)
        /** 车牌号码 */
        case carNum(_: String)
        /** 用户名 */
        case username(_: String)
        /** 密码 */
        case password(_: String)
        /** 昵称 */
        case nickname(_: String)
        /** 网址 */
        case URL(_: String)
        /** IP地址 */
        case IP(_: String)
    
        /** 是否正确 */
        var isRight: Bool {
            var predicateStr:String!
            var currObject:String!
            switch self {
            case let .email(str):
                predicateStr = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
                currObject = str
            case let .phoneNum(str):
                predicateStr = "^((13[0-9])|(15[^4,\\D]) |(17[0,0-9])|(18[0,0-9]))\\d{8}$"
                currObject = str
            case let .carNum(str):
                predicateStr = "^[A-Za-z]{1}[A-Za-z_0-9]{5}$"
                currObject = str
            case let .username(str):
                predicateStr = "^[A-Za-z0-9]{6,20}+$"
                currObject = str
            case let .password(str):
                predicateStr = "^[a-zA-Z0-9]{6,20}+$"
                currObject = str
            case let .nickname(str):
                predicateStr = "^[\\u4e00-\\u9fa5]{4,8}$"
                currObject = str
            case let .URL(str):
                predicateStr = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"
                currObject = str
            case let .IP(str):
                predicateStr = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
                currObject = str
            }
    
            let predicate =  NSPredicate(format: "SELF MATCHES %@" ,predicateStr)
            return predicate.evaluateWithObject(currObject)
        }
    }
    

    调用

    let email = Validate.email("dd_dada23@@163.com").isRight
    print(email) // flase
    
    let url = Validate.URL("https://www.baidu.com").isRight
    print(url) // true
    
    let ip = Validate.IP("11.11.11.11").isRight 
    print(ip) //true
    

    相关文章

      网友评论

          本文标题:记录学习--正则表达式(swift)

          本文链接:https://www.haomeiwen.com/subject/sfgkmttx.html