简体   繁体   English

用R中的单个反斜杠替换斜杠

[英]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. 解决方案是转义转义字符,该字符末尾表示4'\\'。

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()'. 查看标准输出与“ print()”(转义转义字符)之间的区别,或者使用“ cat()”获取纯字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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