代码之家  ›  专栏  ›  技术社区  ›  BlackBox

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

  •  0
  • BlackBox  · 技术社区  · 10 年前

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

    因此,我有一个NSString,它有时会在文本中包含一个图像名称,例如:

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

    我想在那个空间里放一张名为“image”的图片。我的NSMutableAttributedString中的“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 回复  |  直到 10 年前
        1
  •  0
  •   BlackBox    10 年前

    显然我解决了。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];
    }