替换的NSString特定的词(Replace specific words in NSString

2019-08-22 22:57发布

什么是获取和字符串替换特定的词的最好方法? 比如我有

NSString * currentString = @"one {two}, thing {thing} good";

现在我需要找到每个{} currentWord

并应用功能,它

 [self replaceWord:currentWord]

然后从函数结果代替currentWord

-(NSString*)replaceWord:(NSString*)currentWord;

Answer 1:

下面的示例演示了如何使用NSRegularExpressionenumerateMatchesInString来完成任务。 我刚使用uppercaseString作为函数替换一个词,但你可以用你的replaceWord方法,以及:

编辑:我的回答的第一个版本,如果更换的话是更短或更长的原话没有正常工作(感谢费边Kreiser用于提的是!)。 现在,应该在所有情况下正常工作。

NSString *currentString = @"one {two}, thing {thing} good";

// Regular expression to find "word characters" enclosed by {...}:
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:@"\\{(\\w+)\\}"
                                                  options:0
                                                    error:NULL];

NSMutableString *modifiedString = [currentString mutableCopy];
__block int offset = 0;
[regex enumerateMatchesInString:currentString
                        options:0
                          range:NSMakeRange(0, [currentString length])
                     usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
                         // range = location of the regex capture group "(\\w+)" in currentString:
                         NSRange range = [result rangeAtIndex:1];
                         // Adjust location for modifiedString:
                         range.location += offset;

                         // Get old word:
                         NSString *oldWord = [modifiedString substringWithRange:range];

                         // Compute new word:
                         // In your case, that would be
                         // NSString *newWord = [self replaceWord:oldWord];
                         NSString *newWord = [NSString stringWithFormat:@"--- %@ ---", [oldWord uppercaseString] ];

                         // Replace new word in modifiedString:
                         [modifiedString replaceCharactersInRange:range withString:newWord];
                         // Update offset:
                         offset += [newWord length] - [oldWord length];
                     }
 ];


NSLog(@"%@", modifiedString);

输出:

one {--- TWO ---}, thing {--- THING ---} good


文章来源: Replace specific words in NSString