美文网首页iOS精英班零碎知识点
iOS 2017 最新手机号正则判断

iOS 2017 最新手机号正则判断

作者: 上帝也是码农 | 来源:发表于2017-07-12 15:14 被阅读811次

    OC版:

    //判断手机号
    - (BOOL)checkoutPhoneNum: (NSString *)phoneNum {
        NSString *regexStr = @"^1[3,8]\\d{9}|14[5,7,9]\\d{8}|15[^4]\\d{8}|17[^2,4,9]\\d{8}$";
        NSError *error;
        NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
        if (error) return NO;
        NSInteger count = [regular numberOfMatchesInString:phoneNum options:NSMatchingReportCompletion range:NSMakeRange(0, phoneNum.length)];
        if (count > 0) {
            return YES;
        } else {
            return NO;
        }
    }
    

    Swift(3.0.1):

    func checkoutPhoneNum(for regex: String, in phoneNum: String) -> Bool {
        do {
            let regex = try NSRegularExpression(pattern: regex)
            let nsString = phoneNum as NSString
            let results = regex.matches(in: phoneNum, range: NSRange(location: 0, length: nsString.length))
            let resultArray = results.map { nsString.substring(with: $0.range) }
            print(resultArray.count)
            if resultArray.count > 0 {
                return true
            } else {
                return false
            }
        } catch let error {
            print("无效正则表达式: \(error.localizedDescription)")
            return false
        }
    }
    

    参考链接
    github

    相关文章

      网友评论

        本文标题:iOS 2017 最新手机号正则判断

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