NSMutableString replaceOccurrencesOfString replacing whole words

abellina picture abellina · Feb 4, 2013 · Viewed 8.3k times · Source

Is there a way to use replaceOccurrencesOfString (from NSMutableString) to replace whole words?

For example, if I want to replace all occurrences of a fraction in a string, like "1/2", I'd like that to match only that specific fraction. So if I had "11/2", I would not want that to match my "1/2" rule.

I've been trying to look for answers to this already, but I am having no luck.

Answer

James Webster picture James Webster · Feb 4, 2013

You could use word boundaries \b with Regex. This example matches the "1/2" at the start and the end of the example string, but neither of the middle options

// Create your expression
NSString *string = @"1/2 of the 11/2 objects were 1/2ed in (1/2)";

NSError *error = nil;
NSRegularExpression *regex = 
  [NSRegularExpression 
    regularExpressionWithPattern:@"\\b1/2\\b"
                         options:NSRegularExpressionCaseInsensitive
                           error:&error];

// Replace the matches
NSString *modifiedString = 
[regex stringByReplacingMatchesInString:string
                                options:0
                                  range:NSMakeRange(0, [string length])
                           withTemplate:@"HALF USED TO BE HERE"];