stringByReplacing,有例外吗?

Nei*_*eil 3 iphone cocoa-touch ios

假设我有字符串:

@"(Mg(Ni+(N(O2)3";
Run Code Online (Sandbox Code Playgroud)

我想知道是否有可能替换字符串"("的出现次数,但"+("除外).

@"+Mg+Ni+(N+O2)3";
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

omz*_*omz 8

您可以使用正则表达式执行此类更复杂的字符串替换.

您可以使用书写表达负回顾后发现一个(不是前面有一个+(虽然有在这种情况下更简单的方法,看到@ SCH的评论).

例:

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);
Run Code Online (Sandbox Code Playgroud)