简体   繁体   中英

How can I get rid of one backslash in a string in R?

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!

Here you go.

stringr::str_remove_all(stringi::stri_escape_unicode(t1), "\\\\u0")

gives output as

[1] "1002003004005"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM