簡體   English   中英

NSString查找正則表達式並將其替換為圖像(NSMutableAttributeString)

[英]NSString find regular expression and replace it with 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屬性屬於NSString類別。 這是它的代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM