匹配中文字符 [\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