Code:
static NSString* regexReplace(NSString* regexString, NSString* subject, NSString* replacement)
{
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:0 error:nil];
return [regex stringByReplacingMatchesInString:subject options:0 range:NSMakeRange(0, [subject length]) withTemplate:replacement];
}
int main(int argc, const char * argv[])
{
@autoreleasepool
{
NSLog(@"%@", regexReplace(@".*", @"foo", @"bar")); //Output: barbar
NSLog(@"%@", regexReplace(@".+", @"foo", @"bar")); //Output: bar
}
return 0;
}
Why does the “.*” regex replace ‘foo’ with ‘barbar’ instead of ‘bar’?
Because it matches twice: first it matches the
"foo"part, and then it matches an empty""at the end of the"foo".(You can even imagine it matching an infinite number of times, yielding
"barbarbarbar...", but the regex engine is intentionally designed to produce only one empty-string match before moving on, exactly so as to avoid such infinite loops.)