[英]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 = "\\\\"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.