美文网首页
正则表达式

正则表达式

作者: fordring2008 | 来源:发表于2017-02-04 09:28 被阅读13次

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

    }

    相关文章

      网友评论

          本文标题:正则表达式

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