简体   繁体   中英

How to remove '\' from a string using R?

I am trying to remove "\\" from the string "AA0000332\\, AA0000331" and extract AA0000332 and AA0000331 separately.

> string1 <- "AA0000332\, AA0000331"
Error: '\,' is an unrecognized escape in character string starting ""AA0000332\,"

> gsub("[^[:alnum:]///' ]", "","AA0000332\, AA0000331")
Error: '\,' is an unrecognized escape in character string starting ""\,"

> substr("AA0000332\, AA0000331", 1, 9)
Error: '\,' is an unrecognized escape in character string starting ""AA0000332\,"

If all your strings contains letters and numbers then you can try

library(stringr)
string1 <- "AA0000332\\, AA0000331"
unlist(str_extract_all(string1, "([A-Za-z0-9]+)"))

which results in

[1] "AA0000332" "AA0000331"

Try \\\\ , you will have to escape the escape character.

string1 <- "AA0000332\\, AA0000331"
gsub("[^[:alnum:]///' ]", "","AA0000332\\, AA0000331")
[1] "AA0000332 AA0000331"
substr("AA0000332\\, AA0000331", 1, 9)
[1] "AA0000332"

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