用 R 中的单个反斜杠替换斜杠
Replace slash with a single backslash in R
这可能是微不足道的,但我没有找到任何关于这个确切问题的问题。
我的问题与提出合适的正则表达式无关,它与准确指定替换部件有关。
x = "file_path/file_name.txt" - this is what I have
# "file_path\file_name.txt" - this is what I want
这是我尝试过的:
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
如有任何帮助,我们将不胜感激。
解决办法就是转义最后的4个'\'的转义符
cat(gsub('/', '\\', "file_path/file_name.txt"))
看看你的标准输出与转义字符 'print()' 之间的区别,或者使用 'cat()'.
获取纯字符串
str_replace_all(string = x, pattern = "/", replacement = "\\")
cat(str_replace_all(string = x, pattern = "/", replacement = "\\"))
这可能是微不足道的,但我没有找到任何关于这个确切问题的问题。 我的问题与提出合适的正则表达式无关,它与准确指定替换部件有关。
x = "file_path/file_name.txt" - this is what I have
# "file_path\file_name.txt" - this is what I want
这是我尝试过的:
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
如有任何帮助,我们将不胜感激。
解决办法就是转义最后的4个'\'的转义符
cat(gsub('/', '\\', "file_path/file_name.txt"))
看看你的标准输出与转义字符 'print()' 之间的区别,或者使用 'cat()'.
获取纯字符串str_replace_all(string = x, pattern = "/", replacement = "\\")
cat(str_replace_all(string = x, pattern = "/", replacement = "\\"))