Separation of the character into parts

I observe the following symbol:

  l <- "mod, range1 = seq(-m, n, 0.1), range2 = seq(-2, 2, 0.1), range3 = seq(-2, 2, 0.1)"

Using regular expressions in R, I want to split lin the following structure:

[1] "mod"                      "range1 = seq(-m, n, 0.1)"
[3] "range2 = seq(-2, 2, 0.1)" "range3 = seq(-2, 2, 0.1)"

Unfortunately, I have not yet found a way to overcome this problem. Does anyone have an idea how to get such an elegant split?

+4
source share
3 answers

I really doubt that you can do this with regex. You are trying to parse your string, and you need a parser that is usually more powerful than a regular expression. I don’t think it is generic enough, but you can use R-parser and class alist. Try:

res<-eval(parse(text=paste0("alist(",l,")")))
paste0(names(res),ifelse(names(res)!="","=",""),as.character(res))
#[1] "mod"                    "range1=seq(-m, n, 0.1)" "range2=seq(-2, 2, 0.1)"
#[4] "range3=seq(-2, 2, 0.1)"

, , , , . :

l<-"mod, range1 = seq(-m, n, 0.1), range2 = seq(-2, exp(2), 0.1), range3 = seq(-2, 2, 0.1)"

, .

+5

str_extract_all stringr,

library(stringr)
str_extract_all(l, '(?:[^,(]|\\([^)]*\\))+')
#[[1]]
#[1] "mod" " range1 = seq(-m, n, 0.1)" " range2 = seq(-2, 2, 0.1)" " range3 = seq(-2, 2, 0.1)"

trimws(unlist(str_extract_all(l, '(?:[^,(]|\\([^)]*\\))+')))
#[1] "mod" "range1 = seq(-m, n, 0.1)" "range2 = seq(-2, 2, 0.1)" "range3 = seq(-2, 2, 0.1)"
+4

base R, pattern, OP. , ( ), ,, .

strsplit(l, "\\([^)]+\\)(*SKIP)(*F)|, ", perl = TRUE)[[1]]
#[1] "mod"                      "range1 = seq(-m, n, 0.1)"
#[3] "range2 = seq(-2, 2, 0.1)" "range3 = seq(-2, 2, 0.1)"

Update

@nicola 'l'

strsplit(l, ", (?=[[:alnum:]]+\\s+\\=)", perl = TRUE)[[1]]
#[1] "mod"                           "range1 = seq(-m, n, 0.1)"   
#[3]  "range2 = seq(-2, exp(2), 0.1)" "range3 = seq(-2, 2, 0.1)" 

'l'

strsplit(l, ", (?=[[:alnum:]]+\\s+\\=)", perl = TRUE)[[1]]
#[1] "mod"                      "range1 = seq(-m, n, 0.1)" 
#[3] "range2 = seq(-2, 2, 0.1)" "range3 = seq(-2, 2, 0.1)"
+3

All Articles