0

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

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

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

并为其应用功能

 [self replaceWord:currentWord]

然后用函数的结果替换 currentWord

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

1 回答 1

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);

输出:

一个 {--- TWO ---},东西 {--- THING ---} 好
于 2013-04-14T09:57:43.653 回答