テキストのグループで括弧で囲まれたすべての単語を検索し、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..
私の間違いを示すためのガイダンスが必要です。