28

I'm working in R and having troubles escaping the backslash. I am using the library stringr.

install.packages("stringr", repos='http://cran.us.r-project.org')
library("stringr")

I would like to do str = str_replace_all(str, "\", "")

So I tried str = str_replace_all(str, "\\", "") but it won't work.

What should I do?

Paul Fournel
  • 10,807
  • 9
  • 40
  • 68
  • @paul-fournel your solution doesn't work (anymore?) - `gsub("([\])","", "C:\subfolder")` throws the unrecognized escape error. – geotheory Nov 10 '14 at 11:35
  • "C:\subfolder" is not a valid String to start with. If you exectute just this part in the terminal, you will have the same error – Paul Fournel Nov 10 '14 at 13:06
  • 9
    @joran I emailed Achim Zeileis and you'll be in the next release of the `fortunes` package. – Gregor Thomas Mar 12 '15 at 22:54
  • 2
    @csgillespie, would you consider re-opening this question? The question linked as already having the answer does provide an indirect answer. However it takes a little bit of thinking to figure out that if using `str_replace_all` or `gsub`, the string is converted twice, requiring `\\\\ ` as input to get `\ `. The answers here explain just that. Maybe the question title should be changed. – Joooeey Jun 01 '17 at 00:39

2 Answers2

20

I found a solution that works

str = gsub("([\\])","", str)
Paul Fournel
  • 10,807
  • 9
  • 40
  • 68
  • 18
    As per my comment, using `"\\\\"` as a pattern will work as well (with either `gsub` or `str_replace_all`. – joran Feb 14 '13 at 16:25
  • 2
    `gsub("\\", "", str, fixed=TRUE)` would also work. You just need to remember that in R, `\\` is only one character. Try the following: `x <- "my\\strin\\g\\with\\slashes"; print(x); cat(x)`. – A5C1D2H2I1M1N2O1R2T1 Feb 14 '13 at 16:28
  • 2
    In RE, \\ match \. As you need scape every \ to R understand it as \, you need use `gsub("\\\\","", str)`. – Rcoster May 12 '14 at 19:24
  • @paul This code line will work for regular backslashes, but strings like "1\2" get replaced by "1\002", also "5\7" get replaced by "5\a". Why it is so? – indra_patil Jun 03 '16 at 07:23
7

Use Hmisc::escapeRegex and Hmisc::escapeBS which automatically escapes backslashes and other regex special characters.

Ramnath
  • 54,439
  • 16
  • 125
  • 152
  • 2
    Not even `Hmisc` will let you completely `escapeBS`, because ultimately BS is inescapable (especially in programming, and `rep('especially', 2)` in R). – geneorama Dec 21 '16 at 17:13