StringByReplacing, with exceptions?

Let's say I have a line:

@"(Mg(Ni+(N(O2)3";

I am wondering if it is possible to replace the occurrences of the string "(" but with the exception of "+ (". Thus, the result;

@"+Mg+Ni+(N+O2)3";

How should I do it?

+3
source share
3 answers

You can perform this complex string replacement with regular expressions .

You can write an expression using negative lookbehind to find (which is not preceded +(although 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);
+8
source

Read about a similar problem with regular expressions here.

quickfix regexp ( , ):

  • +( [
  • ( +
  • [ +)

, [ . ( , )

+2

There is NSRegularExpressionClassone that provides the following method:

-(NSString *)stringByReplacingMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range withTemplate:(NSString *)template

This is probably what you want.

0
source

All Articles