Reputation: 40437
I'm trying to replace [word]
with \[word\]
using NSRegularExpression
:
NSRegularExpression *metaRegex = [NSRegularExpression regularExpressionWithPattern:@"([\\[\\]])"
options:0
error:&metaRegexError];
NSString *escapedTarget = [metaRegex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, string.length)
withTemplate:@"\\$1"];
But the output of this is $1word$1
. You would think the first \
would escape the second \
character but instead it looks like it's escaping the $
character... How do I tell it to escape \
and not $
?
Upvotes: 3
Views: 1752
Reputation: 43852
You actually need four backslashes, like this:
@"\\\\$1"
Why is this unwieldily system required? Well, think of it this way. The \
character is used as the C escape character and the regex escape character. So, if you create an expression with only one backslash, you might get an error, because the NSString itself will thing you're using the special character \$
. To escape the slash, you need to use two slashes, which will evaluate to only one in the final NSString data.
However, you really need two backslashes in the NSString itself to be sent to the regex parser, so you need to escape two backslashes in the string literal itself. So, \\\\
resolves to \\
in the actual data, which the regex parser then collapses to a single literal \
character
Upvotes: 1
Reputation: 28242
Try:
@"\\\\$1"
for the replacement template. Basically: \\
will escape the \
for the string, so it's @"\$1"
when it's sent to the regex. The \
then escapes the $
in the template, causing your issue.
Upvotes: 3