美文网首页
iOS 正则查找字符串中的数字

iOS 正则查找字符串中的数字

作者: 夏天爱大树 | 来源:发表于2017-08-15 17:21 被阅读1147次

    需求:对字符串中的金额的颜色修改

    传统方法:遍历查找

    NSString *str = @"投资券5.89元";
    if ([str containsString:@"元"])
        {
            NSString *formStr = @"1234567890.";
            NSArray *arr = [str componentsSeparatedByString:@"元"];
            NSString *targetStr = arr.firstObject;
            NSInteger targetLoc;
            if ([formStr containsString:[targetStr substringWithRange:NSMakeRange(targetStr.length-1, 1)]])
            {
                for (NSInteger i=targetStr.length-1; i>=0; i--)
                {
                    if (![formStr containsString:[targetStr substringWithRange:NSMakeRange(i, 1)]])
                    {
                        targetLoc = i+1;
                        break;
                    }
                }
                NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:model.desc];
                [attributedStr addAttribute:NSForegroundColorAttributeName value:UI_THEME_COLOR range:NSMakeRange(targetLoc, targetStr.length-targetLoc)];
                self.descLabel.text = nil;
                self.descLabel.attributedText = attributedStr;
            }
            else
            {
                self.descLabel.text = str;
            }
        }
        else
        {
            self.descLabel.text = model.desc;
        }
    
    

    正则查找

     NSString *str = @"投资券5.89元";
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:str];
        NSRange range = [str rangeOfString:@"\\d[\\d.,]*(?=元)" options:NSRegularExpressionSearch];
        if (range.location != NSNotFound) {
            NSString *subStr = [str substringWithRange:range];
            NSLog(@"%@", subStr);
            
            [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
        }
        self.moneyLabel.attributedText = attStr;
    
    效果图

    相关文章

      网友评论

          本文标题:iOS 正则查找字符串中的数字

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