Reputation: 243
How can I remove all backslashes from this string?
t1 <- "1\2\3\4\5"
Output:
"1\002\003\004\005"
desired output:
"1002003004005"
Thank you!
Upvotes: 1
Views: 550
Reputation: 350
This one is tricky, because "1\002\003\004\005"
isn't really a valid string to begin with. To see this:
> writeLines(t1)
1
However, we can first deparse
it to create valid string.
t2 <- deparse(t1)
> t2
[1] "\"1\\002\\003\\004\\005\""
And then use a regular gsub
to remove the \
and quotes we added as a side effect.
t3 = gsub('\\', '', t2, fixed = TRUE)
t3 = gsub('\"', '', t3)
More ideally, we'd write a compound regex.
t3 = gsub('[(\")(\\)]', '', t2)
> t3
[1] "1002003004005"
Edit: As a oneliner:
gsub('[(\")(\\)]', '', deparse(t1))
You can refer below link for more details on the pattern mapping using gsub:
How do I deal with special characters like \^$.?*|+()[{ in my regex?
https://rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf
Upvotes: 2
Reputation: 1076
Here you go.
stringr::str_remove_all(stringi::stri_escape_unicode(t1), "\\\\u0")
gives output as
[1] "1002003004005"
Upvotes: 1