如何删除' \'从使用R的字符串?

时间:2017-08-10 20:28:34

标签: r

我正在尝试从字符串"\"中删除"AA0000332\, AA0000331"并分别提取AA0000332AA0000331

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

2 个答案:

答案 0 :(得分:2)

如果您的所有字符串都包含字母和数字,那么您可以尝试

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

导致

[1] "AA0000332" "AA0000331"

答案 1 :(得分:2)

尝试\\,你必须逃脱转义字符。

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