Replace regex matches in attributed string with image in Objective-C

a 夏天 提交于 2019-12-04 17:08:24
Josh Caswell

Two problems:

Braces aren't replaced. That's because you're using assertions, which aren't counted as part of the match. The match you're making with your pattern only contains the stuff inside the braces. Use this pattern instead:

\{([^}]+)\}

That's: match a brace, followed by one or more things that aren't closing braces in a capture group, followed by a closing brace. The whole match includes the braces now.

That introduces another problem, though -- you're using the enclosed bits to pick the replacement image. Small change to fix this: the internal capture group holds that information, now, rather than the whole group. The capture group's length tells you the range of the substring you need.

NSUInteger lengthOfManaName = [result rangeAtIndex:1].length;
NSString manaName = [match substringWithRange:(NSRange){1, lengthOfManaName}];
imageAttachment.image = [UIImage imageNamed:[NSString stringWithFormat:@"Mana%@.png", manaName]];

Second problem: length of string is changing. Just enumerate backwards:

for (NSTextCheckingResult *result in [matches reverseObjectEnumerator])
{
    //...
}

Changes to ranges towards the end of the string now won't affect earlier ranges.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!