使用正則表達(dá)式專用類NSRegularExpression來查找位置并設(shè)置顏色
NSString *string = @"滿2科,打88折"
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:self.string];
attStr.font = [UIFont systemFontOfSize:12.0f weight:UIFontWeightSemibold];
attStr.color = [UIColor blackColor];
NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:@"\\d+\\.?\\d*" options:NSRegularExpressionCaseInsensitive error:nil];
[regular enumerateMatchesInString:self.string options:NSMatchingReportCompletion range:NSMakeRange(0, self.string.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
NSRange matchRange = result.range;
NSLog(@"range:%@",NSStringFromRange(matchRange));
[attStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:matchRange];
}];
效果圖:

image.png