0

I have the following string :

G="[-2.798,-1.805)"

I need only the numeric vector [1] -2.798 -1.805 so I try

as.numeric(unique(unlist(regmatches(G, gregexpr("[0-9]+", G)))))

get: [1] 2 798 1 805 but, I don't know what else I could do. Thanks so much

albert
  • 305
  • 4
  • 12
  • 1
    Minor tweek to your regex: `as.numeric(unique(unlist(regmatches(G, gregexpr("-?[0-9.]+", G)))))`. The `?` says 0 or 1 matches and the "." is matched literally in the character class. – lmo Jul 31 '17 at 19:46
  • 1
    Your regex only matches integers. See here: https://stackoverflow.com/questions/2811031/decimal-or-numeric-values-in-regular-expression-validation. But do you really need regex for this? Could just remove the first and last character, then read as array. Would be much faster – jayelm Jul 31 '17 at 19:46
  • 1
    `as.numeric(strsplit(substring(G, 2, nchar(G) - 1), split = ",")[[1]])` – www Jul 31 '17 at 19:53

1 Answers1

0

I think it could be simplified a bit by removing the unique (although processing a bunch of cut boundaries might still need that function). The problem you currently face is not including minus-signs and periods. They can be used in character-class arguments

 as.numeric( unlist(regmatches(G, gregexpr("[-.0-9]+", G))))
[1] -2.798 -1.805
IRTFM
  • 258,963
  • 21
  • 364
  • 487