美文网首页
Swift 正则表达式

Swift 正则表达式

作者: gaookey | 来源:发表于2020-09-11 17:50 被阅读0次
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.utf16.count))
        return matches.count > 0
    }
}
let mailPattern = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"

do {
    let matcher = try RegexHelper(mailPattern)
    let maybeMailAddress = "123@163.com"
    if matcher.match(maybeMailAddress) {
        print("有效的邮箱地址")
    }
} catch { }

自定义符号正则匹配

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 "123@163.com" =~ "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$" {
    print("有效的邮箱地址")
}

摘录来自: 王巍 (onevcat). “Swifter - Swift 必备 Tips (第四版)。”

相关文章

网友评论

      本文标题:Swift 正则表达式

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