【问题标题】:Replace specific words in NSString替换 NSString 中的特定单词
【发布时间】:2013-04-14 09:45:00
【问题描述】:

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

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

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

并为其应用函数

 [self replaceWord:currentWord]

然后用函数的结果替换 currentWord

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

【问题讨论】:

  • 您要替换 { 和 } 中的每个单词吗?
  • 取决于 {} 中的单词所以我需要找到 {word} 然后从中删除单词,替换它然后以某种方式放回去
  • 您的问题不完整。请解释你到底想要什么。您想寻找什么模式等

标签: objective-c nsstring


【解决方案1】:

以下示例显示了如何使用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 ---} 好

【讨论】:

  • 但是,当替换词比原词短或长时,代码不起作用。
  • @FabianKreiser:哎呀,你可能是对的。实际上我有一个更复杂的方法,我试图通过使用NSEnumerationReverse 来简化它,但这个选项似乎在这里不起作用。我会检查并更新答案 - 谢谢!
  • @FabianKreiser:我已经更新了答案,它现在应该可以工作了。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
  • 2014-10-27
  • 2012-05-06
  • 2020-06-11
  • 2021-10-02
  • 1970-01-01
相关资源
最近更新 更多