4

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.

abellina
  • 1,016
  • 1
  • 11
  • 27
  • Would "1/2" always be preceded by a space if it wasn't part of another number? – James Webster Feb 04 '13 at 20:59
  • Thanks for your comment. No, it can be inside of parenthesis "(1/2...)", it can also be at the beginning of the string, and it can be in the middle of the string... – abellina Feb 04 '13 at 21:01
  • i think you should have a look to regular expressions : https://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html – Ultrakorne Feb 04 '13 at 21:03
  • You're going to need to use regular expressions... Similar question: http://stackoverflow.com/questions/6596119/replacing-numbers-in-an-nsstring-with-objects-from-nsarray – James Boutcher Feb 04 '13 at 21:04

1 Answers1

12

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"];
James Webster
  • 31,873
  • 11
  • 70
  • 114
  • 1
    No problem. Don't forget to look for the easy options first as most often the easiest option is usually correct (enough). @H2CO3's option would have been spot on if whitespace was a strict enough delimiter. – James Webster Feb 04 '13 at 21:09