NSString找到正则表达式并将其替换为image(NSMutableAttributeString)

时间:2016-01-01 22:48:40

标签: ios objective-c regex nsstring nsmutableattributedstring

我知道这样的事情已经被问到了,但我找不到解决问题的方法。

所以,我有一个NSString,有时在文本中包含一个图像名称,如:

Lorem ipsum....
image.png
... dolor sit elit lamet

我想在我的NSMutableAttributedString中为该空间添加名为'image.png'的图像。

这是我获取匹配的代码

NSString *regEx = @"([a-z])+(?:([0-9])+){0,1}.png";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:regEx
                              options:NSRegularExpressionCaseInsensitive error:&error];
if(error != nil){
    NSLog(@"Error: %@",error);
} else{
    [regex enumerateMatchesInString:myString options:0 range:NSMakeRange(0, [myString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
        // your code to handle matches here

        NSLog(@"found!");
    }];
}

如何在NSMutableAttributedString中添加图像,为每个找到的子字符串调用imageNamed函数?

1 个答案:

答案 0 :(得分:0)

显然我已经解决了。在for里面有代码用NSMutableAttributedString中的图像替换子字符串。此外,我决定在类似(但不同)的问题中将一个反向的for灵感放在先前的答案中

NSMutableAttributedString *formattedText = myString.mutableAttributedString;

// Look for image
NSString *regEx = @"([a-z])+(?:([0-9])+){0,1}.png";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:regEx
                              options:NSRegularExpressionCaseInsensitive error:&error];
if(error != nil){
    NSLog(@"Error: %@",error);
} else{
    NSArray *matches = [regex matchesInString:myString
                                      options:kNilOptions
                                        range:NSMakeRange(0, myString.length)];
    for (NSTextCheckingResult *result in [matches reverseObjectEnumerator])
    {
        NSString *insideString = [myString substringWithRange:[result rangeAtIndex:0]];
        UIImage *image = [UIImage imageNamed:insideString];
        NSTextAttachment *imageAttachment = [NSTextAttachment new];
        imageAttachment.image = image;
        NSAttributedString *replacementForTemplate = [NSAttributedString attributedStringWithAttachment:imageAttachment];
        [formattedText replaceCharactersInRange:result.range
                           withAttributedString:replacementForTemplate];

        NSLog(@"found! -> %@", insideString);

    }
}

相反,mutableAttributedString属性属于NSString类别。这是它的代码

- (NSMutableAttributedString *)mutableAttributedString {
    return [[NSMutableAttributedString alloc] initWithString:self];
}