Tiago Veloso
Tiago Veloso

Reputation: 8563

How to replace group 1 of a regex with a given string in Objective C

I have the following regex

regex = [NSRegularExpression regularExpressionWithPattern:@"(.*)|(.*)"
                                                  options:NSRegularExpressionCaseInsensitive
                                                    error:&error];

I want to replace the first group of a string matching this regex, with a value from a text field.

For example if I have Hi|Peter and replacing with Goodbye I get Goodbye|Peter

How can I do this?

Upvotes: 1

Views: 2214

Answers (1)

Martin R
Martin R

Reputation: 540065

Is this what you are looking for?

NSString *s1 = @"Hi|Peter";
NSError *error;
NSString *pattern = @"(.*)\\|(.*)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                      options:NSRegularExpressionCaseInsensitive
                                    error:&error];
NSString *s2 = [regex stringByReplacingMatchesInString:s1
                           options:0
                         range:NSMakeRange(0, [s1 length])
                      withTemplate:@"Goodbye|$2"];
NSLog(@"%@", s2);
// Output: Goodbye|Peter

$2 in the replacement template refers to the second capture group. Note that you have to escape the "|" character in the regular expression.

Upvotes: 8

Related Questions