iOS正则方式查找文本内容里包含的手机号,并将中间四位替换为****

//查找文本内容里包含的手机号,并将中间四位替换为****

+ (NSString *)getHiddenPhoneNumberContentTextUseString:(NSString *)originContentText;

{

    NSError *error;

    //设置正则规则:第一位是数字1,接下来后边是10位数字

    NSRegularExpression *attachmentExpression = [NSRegularExpression regularExpressionWithPattern:@"1[\\d]{10}"

    options:NSRegularExpressionCaseInsensitive error:&error];

    //获取符合条件的结果数组

    NSArray *resultArr = [attachmentExpression matchesInString:originContentText options:0 range:NSMakeRange(0, originContentText.length)];

    if (resultArr.count > 0) {

    //遍历结果数组,替换对应位置的字符串

    for (NSTextCheckingResult *tmpResult in resultArr) {

            NSString *tmpStr = [originContentText substringWithRange:tmpResult.range];

            originContentText = [originContentText stringByReplacingCharactersInRange:tmpResult.range withString:[NSString getHiddenPhoneNumberUseString:tmpStr]];

        }

    }

        return originContentText;

}

 

//替换手机号中间四位为****

+ (NSString *)getHiddenPhoneNumberUseString:(NSString *)originPhoneNumber

{

//校验长度,防止传入数据不对引起崩溃

    if (originPhoneNumber.length >= 7) {

        return [originPhoneNumber stringByReplacingOccurrencesOfString:[originPhoneNumber substringWithRange:NSMakeRange(3,4)] withString:@"****"];

    } else {

        return originPhoneNumber;

    }

}

你可能感兴趣的:(iOS,Object-C)