rcharacter-replacement

Replace slash with a single backslash in R


This is probably trivial, but I have failed to find any question referring to this exact issue. My issue does not have to do with coming up with a suitable regex, it has to do with accurately specifying the replacement part.

x = "file_path/file_name.txt" - this is what I have
# "file_path\file_name.txt" - this is what I want

Here is what I tried:

library(stringr)
str_detect(string = x, pattern = "/") # returns TRUE, as expected
#str_replace_all(string = x, pattern = "/", replacement = "\") # fails, R believes I'm escaping the quote in the replacement
str_replace_all(string = x, pattern = "/", replacement = "\\") # this results to "file_pathfile_name.txt", missing the backslash altogether
str_replace_all(string = x, pattern = "/", replacement = "\\\\") # this results to "file_path\\file_name.txt", which is not what I want

Any help would be greatly appreciated.


Solution

  • The solution is to escape the escape character which means 4 '\' in the end.

    cat(gsub('/', '\\\\', "file_path/file_name.txt"))
    

    Look at the difference between your standard output with like 'print()' which escapes the escape character, or get the plain string by using 'cat()'.

    str_replace_all(string = x, pattern = "/", replacement = "\\\\")
    cat(str_replace_all(string = x, pattern = "/", replacement = "\\\\"))