使用正则判断字符串中的手机号

-(void)distinguishPhoneNumLabel:(UILabel *)label labelStr:(NSString *)labelStr{

//获取字符串中的电话号码
NSString *regulaStr = @"\\d{3,4}[- ]?\\d{7,8}";
NSRange stringRange = NSMakeRange(0, labelStr.length);
//正则匹配
NSError *error;

 NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:labelStr];

NSRegularExpression *regexps = [NSRegularExpression regularExpressionWithPattern:regulaStr options:0 error:&error];
if (!error && regexps != nil) {
    [regexps enumerateMatchesInString:labelStr options:0 range:stringRange usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {

        NSRange phoneRange = result.range;
        //定义一个NSAttributedstring接受电话号码字符串
        phoneNumber = [str attributedSubstringFromRange:phoneRange];
        //添加下划线
        NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
        [str addAttributes:attribtDic range:phoneRange];
        //设置文本中的电话号码显示为黄色
        [str addAttribute:NSForegroundColorAttributeName value:[LFWImage colorWithHexString:@"FF8200"] range:phoneRange];

        label.attributedText = str;
        label.userInteractionEnabled = YES;

        //添加手势,可以点击号码拨打电话
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];

        [label addGestureRecognizer:tap];

    }];
}

}

来源:
作者:陨之希留leo 链接:http:
//www.jianshu.com/p/24758065047d

 

posted @ 2017-08-27 22:41  新司机上路  阅读(1688)  评论(0编辑  收藏  举报
本人qq1365102044,有问题欢迎沟通!