Skip to content
Prev 180513 / 398503 Next

replace "%" with "\%"

Marc Schwartz wrote:
this confusing "backslash each backslashing backslash" scheme is
idiosyncratic to r;  in many cases where one'd otherwise use a single
backslash in a regex or a replacement string in another programming
language, in r you have to double it.

and actually, in this case you don't need four backslashes.  the
original poster has actually had a valid solution, but he wasn't aware
that the string "\\%", returned (not printed) by gsub includes two, not
three characters --  thus only one backslash, not two:

    cat(
        gsub(
            pattern='%',
            replacement='\\%',
            x='foo % bar',
            fixed=TRUE))
    # foo \% bar

of course, if the pattern cannot be fixed, i.e., fixed=TRUE is less than
helpful, you'd need four backslashes in the replacement -- a cute,
though somewhat disturbing, weirdo.

vQ