Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableString replaceOccurrencesOfString replacing whole words

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.

like image 398
abellina Avatar asked Dec 16 '22 14:12

abellina


1 Answers

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"];
like image 55
James Webster Avatar answered Jan 11 '23 23:01

James Webster