Replace specific words in NSString

穿精又带淫゛_ 提交于 2019-12-20 05:43:23

问题


what is the best way to get and replace specific words in string ? for example I have

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

now I need find each {currentWord}

and apply function for it

 [self replaceWord:currentWord]

then replace currentWord with result from function

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

回答1:


The following example shows how you can use NSRegularExpression and enumerateMatchesInString to accomplish the task. I have just used uppercaseString as function that replaces a word, but you can use your replaceWord method as well:

EDIT: The first version of my answer did not work correctly if the replaced words are shorter or longer as the original words (thanks to Fabian Kreiser for noting that!) . Now it should work correctly in all cases.

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

Output:

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


来源:https://stackoverflow.com/questions/15997712/replace-specific-words-in-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!