处理字符串
NSString * regExpStr = @"(\\d{3})\\d{4}(\\d{0,4})";
NSString *resultString = [self stringByReplacingOccurrencesOfRegex:regExpStr withString:@"$1****$2"];
return resultString;
处理属性字符串
- (NSAttributedString *)replacePhoneNumber:(NSAttributedString *)sourceString
{
NSString * regExpStr = @"(\\d{3})\\d{4}(\\d{0,4})";
NSString *str = [sourceString string];
NSDictionary *attr = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
NSAttributedString *replacement = [[NSAttributedString alloc] initWithString:@"****" attributes:attr];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regExpStr options:0 error:nil];
NSArray* matches = [regex matchesInString:str
options:NSMatchingWithoutAnchoringBounds
range:NSMakeRange(0, sourceString.length)];
NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithAttributedString:sourceString];
for (NSTextCheckingResult* result in [matches reverseObjectEnumerator]) {
NSRange matchRange = [result range];
[resultString replaceCharactersInRange:NSMakeRange(matchRange.location+3, 4) withAttributedString:replacement];
}
return resultString;
}