0

Say I have a string that contains a control code "\f3" (yes it is RTF). I want to replace that control code with another string. At the moment I am using [mutableString replaceOccurrencesOfString:@"\f3" withString:@"replacement string" options:0 range:NSMakeRange(0, [mutableString length])];

This works fine, however sometimes the code can be "\f4" or even "\f12" for example. How do I replace these strings? I could use replaceOccurrencesOfString for each, but the better way to do it is using wildcards, as it could be any number.

colincameron
  • 2,696
  • 4
  • 23
  • 46

1 Answers1

2

Regular expressions would do it.

Take a look at NSRegularExpression (iOS >= 4) and this page for how regular expressions work.

You will want something like:

// Create your expression
NSError *error = nil;
NSRegularExpression *regex = 
  [NSRegularExpression regularExpressionWithPattern:@"\\b\f[0-9]*\\b"
                                            options:NSRegularExpressionCaseInsensitive
                                              error:&error];

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

WARNING : I've not tested my regaular expression and I'm not that great at getting them right first time; I just know that regular expressions are the way forward for you and it has to look something like that ;)

deanWombourne
  • 38,189
  • 13
  • 98
  • 110
  • Excellent! That's just what I was looking for. I thought it was something to do with regular expressions, but have always avoided them up until now! Guess I have to get learning. – colincameron Nov 16 '11 at 12:07