[英]Replace \ into // using gsub in R
I am trying to replace x
variable data E:\\testCSV.csv
to E://testCSV.csv
using gsub
function.. 我正在尝试使用
gsub
函数将x
变量数据E:\\testCSV.csv
为E://testCSV.csv
。
> x
[1] "E:\testCSV.csv"
> gsub("\", "//", x, fixed = TRUE)
Error: unexpected '/' in "gsub("\", "//"
tried all combinations of escape strings, including brackets []
with no success. 尝试了转义字符串的所有组合,包括方括号
[]
,均未成功。 Please suggest 请建议
We may need 我们可能需要
sub("^([^:]+\\:).(.*)", "\\1//t\\2", str1)
#[1] "E://testCSV.csv"
The reason it is not working is because t
is escaped ie it represents for tab ( \\t
). 它不起作用的原因是因为
t
被转义,即代表制表符( \\t
)。 To check it, we can use cat
. 要检查它,我们可以使用
cat
。
cat(str1, sep="\n")
#E: estCSV.csv
Usually, we cannot create a string with a single \\
in R if it doesn't have any meaning. 通常,如果在R中没有任何意义,我们将无法创建带有单个
\\
的字符串。
str2 <- "E:\zestCV.csv"
#Error: '\z' is an unrecognized escape in character string starting ""E:\z"
We need to escape it with a second \\
. 我们需要再转义
\\
。
str2 <- "E:\\zestCV.csv"
str2
#[1] "E:\\zestCV.csv"
To replace that, the method showed by the OP (slightly different) should work. 要替换它,OP应该显示的方法(略有不同)应该起作用。
sub("\\\\", "//", str2)
#[1] "E://zestCV.csv"
str1 <- "E:\testCSV.csv"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.