Reputation: 8563
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
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