I am trying to find all the words with brackets around them in a group of text and change it to italics in iOS. I use this code to find brackets in the text:
static inline NSRegularExpression * ParenthesisRegularExpression() { static NSRegularExpression *_parenthesisRegularExpression = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _parenthesisRegularExpression = [[NSRegularExpression alloc] initWithPattern:@"\\[[^\\(\\)]+\\]" options:NSRegularExpressionCaseInsensitive error:nil]; }); return _parenthesisRegularExpression; }
I use this to show me matches:
NSRange matchRange = [result rangeAtIndex:0]; NSString *matchString = [[self.markerPointInfoDictionary objectForKey:@"long_description"] substringWithRange:matchRange]; NSLog(@"%@", matchString);
But he returns me all the text from the first [to the last] in the group of text. Between them there are many brackets.
I use this code to change the text to italics:
-(TTTAttributedLabel*)setItalicTextForLabel:(TTTAttributedLabel*)attributedLabel fontSize:(float)Size { [attributedLabel setText:[self.markerPointInfoDictionary objectForKey:@"long_description"] afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) { NSRange stringRange = NSMakeRange(0, [mutableAttributedString length]); NSRegularExpression *regexp = ParenthesisRegularExpression(); UIFont *italicSystemFont = [UIFont italicSystemFontOfSize:Size]; CTFontRef italicFont = CTFontCreateWithName((__bridge CFStringRef)italicSystemFont.fontName, italicSystemFont.pointSize, NULL); [regexp enumerateMatchesInString:[mutableAttributedString string] options:0 range:stringRange usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange matchRange = [result rangeAtIndex:0]; NSString *matchString = [[self.markerPointInfoDictionary objectForKey:@"long_description"] substringWithRange:matchRange]; NSLog(@"%@", matchString); if (italicFont) { [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName range:result.range]; [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)italicFont range:result.range]; CFRelease(italicFont); NSRange range1 = NSMakeRange (result.range.location, 1); NSRange range2 = NSMakeRange (result.range.location + result.range.length -2 , 1); [mutableAttributedString replaceCharactersInRange:range1 withString:@""]; [mutableAttributedString replaceCharactersInRange:range2 withString:@""]; } }]; return mutableAttributedString; }]; return attributedLabel; }
Btw my Text looks like this:
[hello] welcome [world], my [name] is [lakesh]
The results look like this:
match string is [hello] match string is [world] match string is is [lak then crash..
Need to be guided to show me my mistake.