在项目中集成 regexkitlite 集成 网上有教程
- (NSMutableAttributedString *)extractBracketsContentSelectAttrs:(NSDictionary *)selectAttr noSelectAttrs:(NSDictionary *)noSelectAttr{//字典为富文本
NSString *str = [NSString stringWithString:self];
NSString *regex = @"(?<=\\()(.+?)(?=\\))";//()正则
NSArray *matchStrArr = [self componentsMatchedByRegex:regex];//regexkitlite提取()中内容可能有多个()返回数组
str = [str stringByReplacingOccurrencesOfString:@"(" withString:@""];
str = [str stringByReplacingOccurrencesOfString:@")" withString:@""];
NSRange remainRange = NSMakeRange(0, str.length);
NSMutableArray *ranges = [[NSMutableArray alloc] initWithCapacity:matchStrArr.count];
for (NSString *indexStr in matchStrArr) {
NSRange firstRange = [str rangeOfString:indexStr options:NSCaseInsensitiveSearch range:remainRange];
NSValue * rangeValue = [NSValue valueWithRange:firstRange];
[ranges addObject:rangeValue];
NSUInteger endLocation = firstRange.location + firstRange.length;
remainRange = NSMakeRange(endLocation, str.length - endLocation);
}
NSMutableAttributedString *mutableStr = [[NSMutableAttributedString alloc] initWithString:str];
[mutableStr addAttributes:noSelectAttr range:NSMakeRange(0, mutableStr.length)];
for (NSValue *value in ranges) {
[mutableStr addAttributes:selectAttr range:value.rangeValue];
}
return mutableStr;
}