替换NSString中的特定单词

时间:2013-04-14 09:45:00

标签: objective-c nsstring

获取和替换字符串中特定单词的最佳方法是什么? 例如,我有

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

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

并为其应用功能

 [self replaceWord:currentWord]

然后将currentWord替换为函数

的结果
-(NSString*)replaceWord:(NSString*)currentWord;

1 个答案:

答案 0 :(得分:3)

以下示例说明如何使用NSRegularExpressionenumerateMatchesInString完成任务。我刚刚使用uppercaseString作为替换单词的函数,但您也可以使用replaceWord方法:

编辑:如果替换的单词是,我的答案的第一个版本无法正常工作 比原始单词更短或更长(感谢Fabian 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