Aleph0
Aleph0

Reputation: 6084

Extract vector of unquoted strings from string of quoted strings

I have a string of the form:

str<-"    'A'    'B'    'csdsdf3' 'csdsdf3' "

I'm looking for the simplest function u<-extract(str), which gives

u=c("A","B","csdsdf3", "csdsdf3")

I already tried strsplit, but it doesn't give the desired result. I'm using R relatively seldom and I'm overwhelmed by the multitude of functions. Most likely a regular expression could be helpful to extract the strings inside the quotes, but I don't know how to do it.

Upvotes: 0

Views: 82

Answers (2)

akrun
akrun

Reputation: 887881

We can use str_extract to match characters that are not a ' or space

library(stringr)
u1 <- str_extract_all(str, "[^' ]+")[[1]]
identical(u, u1)
#[1] TRUE

Or if we use strsplit, split on the ' and space

u2 <- strsplit(str, "[' ]")[[1]]
u2[nzchar(u2)]

Upvotes: 2

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

Why not just use scan?

scan(what = "", text = str)
# Read 4 items
# [1] "A"       "B"       "csdsdf3" "csdsdf3"

Upvotes: 5

Related Questions