简体   繁体   中英

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.

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 = "\\\\"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM