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 ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.