如何从R中的字符中删除反斜杠?

 收藏

我不敢相信这很难。

t1 <- "1\2\3\4\5"

什么是行不通的。

t1 <- gsub('\\','', t1)
t1 <- gsub('\\\\','', t1)
str_remove(t1, "\\")
str_remove(t1, "\\\\")

什么也不起作用:

  1. 正则表达式删除所有非字母数字字符。 (这是一个示例,文本比HTML / Javascript / SVG更复杂)。

附注:我确实在这里和伯克利教授的书中看到了类似问题的其他答案。不行

回复
  • In fact, your second attempt with gsub is actually correct:

    t1 <- gsub("\\\\", "", t1)
    

    A literal backslash in regex requires four backslashes (two each for a literal backslash, one of which is required to escape the other backslash). The reason the above appears to not work is that the string t1 was defined incorrectly. You should have defined it as:

    t1 <- "1\\2\\3\\4\\5"
    gsub("\\\\", "", t1)
    [1] "12345"
    

    A literal backslash in an R character literal requires two backslashes. What you defined originally as t1 is actually a bunch of control characters:

    t1 <- "1\2\3\4\5"