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



我知道已经有人问过这样的问题,但我没有找到解决问题的方法。

所以,我有一个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函数?

显然我解决了这个问题。在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属性属于NSStringCategory。这是的代码

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

最新更新