Replace specific words in NSString

后端 未结 1 1356
不思量自难忘°
不思量自难忘° 2021-01-26 09:15

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

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

相关标签:
1条回答
  • 2021-01-26 09:32

    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
    0 讨论(0)
提交回复
热议问题