RanonKahn
RanonKahn

Reputation: 862

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\,"

Upvotes: 0

Views: 136

Answers (2)

ekstroem
ekstroem

Reputation: 6181

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"

Upvotes: 2

Rui Barradas
Rui Barradas

Reputation: 76460

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"

Upvotes: 2

Related Questions