如何为Smilyes iOS生成正则表达式?

如何为Smilyes iOS生成正则表达式?,ios,objective-c,regex,Ios,Objective C,Regex,我已经在我的情况下尝试了上面的代码,但它不起作用。请帮助我,我想替换[$-1]…[$-9],$-a]…[$-g]的smileys 例如,对于字符串“这是我的笑脸[$-1]它看起来漂亮[$-a]值”,它应该替换为2个笑脸,替换为[$-1],[$-a]结果应该是这样的“这是我的笑脸(@Smiley)它看起来漂亮(@Smiley)值” 为此,我们使用以下代码 NSString *formattedText = @"This is my Smilyes [$-1] it looks beautiful

我已经在我的情况下尝试了上面的代码,但它不起作用。请帮助我,我想替换[$-1]…[$-9],$-a]…[$-g]的smileys

例如,对于字符串
“这是我的笑脸[$-1]它看起来漂亮[$-a]值”
,它应该替换为2个笑脸,替换为
[$-1]
[$-a]
结果应该是这样的
“这是我的笑脸(@Smiley)它看起来漂亮(@Smiley)值”

为此,我们使用以下代码

NSString *formattedText = @"This is my Smilyes [$-1] it looks beautiful [$-a] The Value"; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\[\$\-1\])|(\[\$\-2\])|(\[\$\-3\])|(\[\$\-4\])|(\[\$\-5\])|(\[\$\-6\])|(\[\$\-7\])|(\[\$\-8\])|(\[\$\-9\])|(\[\$\-a\])|(\[\$\-b\])|(\[\$\-c\])|(\[\$\-d\])|(\[\$\-e\])|(\[\$\-f\])|(\[\$\-g\])" options:NSRegularExpressionAnchorsMatchLines error:nil];

NSArray *matches = [regex matchesInString:formattedText
                                  options:kNilOptions
                                    range:NSMakeRange(0, formattedText.length)];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:formattedText];
for (NSTextCheckingResult *result in matches)
{

    NSString *match = [formattedText substringWithRange:result.range];
    NSTextAttachment *imageAttachment = [NSTextAttachment new];
    imageAttachment.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@.png", match]];
    NSAttributedString *replacementForTemplate = [NSAttributedString attributedStringWithAttachment:imageAttachment];
    [attributedString replaceCharactersInRange:result.range
                          withAttributedString:replacementForTemplate];

    NSLog(@"Matches are = %@",match);
}

[_textView setAttributedText:attributedString];
匹配项正确,分别为[$-1]和[$-a]

但是输出是这样的这是我的笑脸(@Smiley)它看起来很漂亮[$-a(@Smiley)值


我想知道问题出在哪里如果匹配很好,那么为什么它不会替换精确的匹配它只是用smiley替换“[$-1]”和“]用smiley替换“[$-1]”试试这个
@“\[\$-[123456789abcdefg]\]”没有解决的问题是一样的,只需先替换[$-1]对于笑脸,但当我为笑脸添加多个代码时,它只是从第5个字符“]”开始替换笑脸,并在“]”之后再替换四个字符