我正在尝试在一组文本中搜索所有带有括号的单词,并在 iOS 中将其更改为斜体。我正在使用此代码在文本中搜索括号:
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;
}
我用它来向我展示比赛:
NSRange matchRange = [result rangeAtIndex:0];
NSString *matchString = [[self.markerPointInfoDictionary objectForKey:@"long_description"] substringWithRange:matchRange];
NSLog(@"%@", matchString);
但它正在向我返回文本组中从第一个 [ 到最后一个 ] 的所有文本。中间有很多括号。
我正在使用此代码将文本更改为斜体:
-(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;
}
顺便说一句,我的文本看起来像这样:
[hello] welcome [world], my [name] is [lakesh]
结果如下所示:
match string is [hello]
match string is [world]
match string is is [lak
then crash..
需要一些指导来告诉我我的错误。