[R] Regexp pattern but fixed replacement?

Enrico Schumann e@ @end|ng |rom enr|co@chum@nn@net
Thu May 23 11:24:52 CEST 2024


On Thu, 11 Apr 2024, Duncan Murdoch writes:

> I noticed this issue in stringr::str_replace, but it
> also affects sub() in base R.
>
> If the pattern in a call to one of these needs to be a
> regular expression, then backslashes in the replacement
> text are treated specially.
>
> For example,
>
>   gsub("a|b", "\\", "abcdef")
>
> gives "def", not "\\\\def" as I wanted.  To get the
> latter, I need to escape the replacement backslashes,
> e.g.
>
>   gsub("a|b", "\\\\", "abcdef")
>
> which gives "\\\\cdef".
>
> I have two questions:
>
> 1.  Is there a variant on sub or str_replace which
> allows the pattern to be declared as a regular
> expression, but the replacement to be declared as
> fixed?

I realize that this reply is late, but you can use raw
strings for the replacement:

   gsub("a|b", r"(\\)", "abcdef")
   ## [1] "\\\\cdef"

which might be easier to read, sometimes.

[...]

-- 
Enrico Schumann
Lucerne, Switzerland
http://enricoschumann.net



More information about the R-help mailing list