美文网首页
iOS使用正则查找字符串中的数字并改变字体颜色

iOS使用正则查找字符串中的数字并改变字体颜色

作者: 小驴拉磨 | 来源:发表于2020-06-19 15:16 被阅读0次

使用正则表达式专用类NSRegularExpression来查找位置并设置颜色

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

相关文章

网友评论

      本文标题:iOS使用正则查找字符串中的数字并改变字体颜色

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