You may use
gsub("&", "\\&", "A&B",fixed=TRUE) # Fixed string replacement
gsub("(&)", "\\\\\\1", "A&B") # Regex replacement
The fixed string replacement is clear: every &
is replaced with a \&
. The double \
is used in the string literal to denote a literal \
.
In the regex replacement, the &
is matched and captured into Group 1. Since a backslash is a special character in the regex replacement pattern, it must be doubled, and - keeping in mind a literal backslash is defined with \\
inside a string literal - we need to use \\\\
in the replacement. The \1
is the backreference to Group 1 value, but again, the \
must be doubled in the string, literal, hence, we use \\1
in there. That is why there are 6 backslashes in a row. You may find more about backslashes problem here.
The result only contains a single backslash, you can easily check that using cat
or saving the contents to a text file:
cat(gsub("&", "\\&", "A&B",fixed=TRUE), collapse="\n")
cat(gsub("(&)", "\\\\\\1", "A&B"))
See the R demo online