解析括号和引号

时间:2019-06-07 14:40:48

标签: r regex stringr

我有一个字符串向量,我想解析它。但是,方括号加上引号会使情况变得相当复杂。我想最好用stringr解决这个问题(不是必须的)

x = c("[\"DER001_A375_96H:TRCN0000052583:-666\"]", "[\"TRCN0000052583\"]", "[\"AAK1\",\"AARS\"]", "[\"A375\"]", "-6.7389873 ... 4.6063291") 

> x
[1] "[\"DER001_A375_96H:TRCN0000052583:-666\"]" "[\"TRCN0000052583\"]"                     
[3] "[\"AAK1\",\"AARS\"]"                       "[\"A375\"]"                               
[5] "-6.7389873 ... 4.6063291"    

预期结果:

DER001_A375_96H:TRCN0000052583:-666
TRCN0000052583
AAK1
AARS
A375
6.7389873
4.6063291

2 个答案:

答案 0 :(得分:2)

用逗号替换...的每次出现,并删除所有出现的方括号。 (请注意,[...]定义了一个字符类,如果该类中的第一个字符为],则该字符将被视为该类的一部分,而不是终止符]。 )最后,使用scan进行阅读。不使用任何软件包。

scan(text = gsub('[][]', '', gsub(" ... ", ",", x, fixed = TRUE)), 
  sep = ",", what = "", quiet = TRUE)

给予:

[1] "DER001_A375_96H:TRCN0000052583:-666" "TRCN0000052583"                     
[3] "AAK1"                                "AARS"                               
[5] "A375"                                "-6.7389873"                         
[7] "4.6063291"                     

答案 1 :(得分:1)

借助SO(用于分析字符串)和http://edrub.in/CheatSheets/cheatSheetStringr.pdf

x = c("[\"DER001_A375_96H:TRCN0000052583:-666\"]", 
      "[\"TRCN0000052583\"]", "[\"AAK1\",\"AARS\"]", 
      "[\"A375\"]", "-6.7389873 ... 4.6063291") 
library("dplyr", quietly = TRUE, warn.conflicts = FALSE)
x1 <- x %>% 
        stringr::str_remove_all(pattern = "\"" ) %>% 
        stringr::str_remove_all(pattern = "\\[" ) %>% 
        stringr::str_remove_all(pattern = "\\]" )

x2 <- unlist ( strsplit(x1, split = ",") )
x3 <- unlist ( strsplit(x2, split = "\\.\\.\\.") )
x3
#> [1] "DER001_A375_96H:TRCN0000052583:-666"
#> [2] "TRCN0000052583"                     
#> [3] "AAK1"                               
#> [4] "AARS"                               
#> [5] "A375"                               
#> [6] "-6.7389873 "                        
#> [7] " 4.6063291"

reprex package(v0.2.1)于2019-06-07创建