获取一行文本中 一个连续数字的起始位置和长度

应用场景:一般应用于连续签到的提示,部分文本中需要特殊显示的数字样式

- (NSRange)rangeOfFirstMatchString:(NSString *)str{
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators | NSRegularExpressionAnchorsMatchLines | NSRegularExpressionAllowCommentsAndWhitespace error:&error];
    NSRange firstMatchRange = [regex rangeOfFirstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
    NSInteger matches = [regex numberOfMatchesInString:str options:0 range:NSMakeRange(0, [str length])];
    if (matches>1) {
        firstMatchRange.length = firstMatchRange.length + matches - 1;
    }
    return firstMatchRange;
}

接下来就可以利用返回的range值设置attributeString的富文本的属性,例如:

- (void)setAttributeStringForBlackLbl:(NSString *)str{
    if ([NSString contentIsNullORNil:str] ==  NO) {
        NSMutableAttributedString * attributeString = [[NSMutableAttributedString alloc] initWithString:str];
        [attributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, str.length)];
        [attributeString addAttribute:NSForegroundColorAttributeName value:[UIColor colorFromHexRGB:@"FF533D"] range:NSMakeRange(0, str.length)];
        //设置强调文字
        NSRange specialRange = [self rangeOfFirstMatchString:str];
        [attributeString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:18.0] range:specialRange];
        [attributeString addAttribute:NSForegroundColorAttributeName value:[UIColor colorFromHexRGB:@"E24C39"] range:specialRange];
        self.blackLbl.attributedText = attributeString;
    }
}

 

转载于:https://www.cnblogs.com/tianlin106/p/9075459.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值