How to get all NSRange of a particular character in a NSString?

后端 未结 4 1873
醉酒成梦
醉酒成梦 2020-12-10 11:21

I have two NSStrings: orgText and searchLetter.
I want to highlight every occurrences of the searchLetter in the orgText with a re

4条回答
  •  悲哀的现实
    2020-12-10 12:03

    I'm not seeing any solution with regular expression, so I've created an elegant one, it may be useful for someone in the future.

    - (BOOL)highlightString:(NSString *)string inText:(NSMutableAttributedString *)attributedString withColour:(UIColor *)color {
        NSError *_error;
        NSRegularExpression *_regexp = [NSRegularExpression regularExpressionWithPattern:string options:NSRegularExpressionCaseInsensitive error:&_error];
        if (_error == nil) {
            [_regexp enumerateMatchesInString:attributedString.string options:NSMatchingReportProgress range:NSMakeRange(0, attributedString.string.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
                if (result.numberOfRanges > 0) {
                    for (int i = 0; i < result.numberOfRanges; i++) {
                        [attributedString addAttribute:NSBackgroundColorAttributeName value:color range:[result rangeAtIndex:i]];
                    }
                }
            }];
            return TRUE;
        } else {
            return FALSE;
        }
    }
    

提交回复
热议问题