iOS 改变字符串中数字的颜色

匹配中文字符 [\u4e00-\u9fa5]

匹配双字节字符(包括汉字在内) [^\x00-\xff]

匹配网址:[a-zA-z]+://[^\s]*

匹配国内电话 \d{3}-\d{8}|\d{4}-\{7,8}

匹配腾讯QQ号 [1-9][0-9]{4,}

匹配18位身份证号^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$

Swift String

//
//  ModifyNumberColor.swift
//  CodeBench
//
//  Created by coder on 2019/8/7.
//  Copyright © 2019 AlexanderYeah. All rights reserved.
//

import Foundation
import UIKit


extension String {
    
    /// 改变字符串中数字的颜色和字体
    ///
    /// - Parameters:
    ///   - color: 颜色
    ///   - font: 字体
    ///   - regx: 正则 默认数字 "\\d+"
    /// - Returns: attributeString
    
    
    
    func modifyNumberColor(color: UIColor,
                      font: UIFont,
                      regx: String = "([0-9]\\d*\\.?\\d*)") -> NSMutableAttributedString {
        let attributeString = NSMutableAttributedString(string: self)
        do {
            // 数字正则表达式
            let regexExpression = try NSRegularExpression(pattern: regx, options: NSRegularExpression.Options())
            let result = regexExpression.matches(
                in: self,
                options: NSRegularExpression.MatchingOptions(),
                range: NSMakeRange(0, count)
            )
            for item in result {
                attributeString.setAttributes(
                    [.foregroundColor : color, .font: font],
                    range: item.range
                )
            }
        } catch {
            print("Failed with error: \(error)")
        }
        return attributeString
    }
}


OC 扩展

//
//  NSString+ModifyDigitalColor.m
//  CreateWitSaleManager
//
//  Created by coder on 2019/8/7.
//  Copyright © 2019 Wangxc. All rights reserved.
//

#import "NSString+ModifyDigitalColor.h"

@implementation NSString (ModifyDigitalColor)



- (NSMutableAttributedString *)modifyDigitalColor:(UIColor *)color normalColor:(UIColor *)normalColor;
{
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:@"([0-9]\\d*\\.?\\d*)" options:0 error:NULL];
    
    NSArray<NSTextCheckingResult *> *ranges = [regular matchesInString:self options:0 range:NSMakeRange(0, [self length])];
    
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:self attributes:@{NSForegroundColorAttributeName : normalColor}];
    
    for (int i = 0; i < ranges.count; i++) {
        [attStr setAttributes:@{NSForegroundColorAttributeName : color} range:ranges[i].range];
    }
    return attStr;
}



@end

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值