I’m trying to find and replace any occurrence of [URL] in an NSString. This is my approach:
NSString *test = @"Test [URL] 123";
test = [test stringByReplacingOccurrencesOfString:@"[URL]"
withString:@"HERE"
options:NSRegularExpressionSearch
range:NSMakeRange(0, test.length)];
The result of this is Test [HEREHEREHERE] 123.
I guess it’s because [URL] means any of those 3 characters, so all 3 characters will be replaced with HERE one after another.
However I also tried \[URL\] with the same result.
So, how do I actually search for the characters [ and ]?
You are absolutely right about diagnosing your problem: the square brackets are meta-characters in the regular expression language, so they get interpreted by the regex engine.
You need to double-escape your slashes, because they are special characters in both Objective-C and regexp language:
@"\\[URL\\]"