stringByReplacing, with exceptions?

cocoa-touch, ios, iphone

Solution

You can do this sort of more complex string replacements with regular expressions.

You can write the expression using a negative lookbehind to find a `(` that is not preceded by a `+` (though there are simpler alternatives in this case, see @sch's comment).

Example:

NSString *string = @"(Mg(Ni+(N(O2)3";
NSLog(@"Original string: %@", string);
NSString *pattern = @"(?<!\\+)\\(";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:NULL];   
NSString *modifiedString = [regex stringByReplacingMatchesInString:string 
                                                           options:0
                                                             range:NSMakeRange(0, [string length])
                                                      withTemplate:@"$1+"];
NSLog(@"After replacement: %@", modifiedString);

Problem

Let's say I have the string: ``` @"(Mg(Ni+(N(O2)3"; ``` I am wondering if it is possible to replace occurrences of the string "(" but with the exception of "+(". Thus result; ``` @"+Mg+Ni+(N+O2)3"; ``` How would I go about doing this?

Original source