I am trying to convert an expression such as [[a], [b]] into list(c(a), c(b)) (basically a java dictionary into R list). As a first step, I would like to convert each inner expression [a] into an equivalent c(a). According to How to replace square brackets with curly brackets using R's regex?, I can use a nice regular expression "\\[(.*?)\\]" or also \\[([^]]*)\\].
This will work when there is only one [] parenthesis, but not multiple ones like [[ as it will capture the first, resulting in "c([a), c(b])" instead of "[c(a), c(b)]". How can I make sure I am only matching the inner parenthesis in a call that contains multiple [[], []]?
vec <- c("[a]", "[[a], [b]]")
gsub("\\[(.*?)\\]", "c(\\1)", vec)
#> [1] "c(a)" "c([a), c(b])"
gsub("\\[([^]]*)\\]", "c(\\1)", vec)
#> [1] "c(a)" "c([a), c(b)]"
Created on 2021-02-15 by the reprex package (v0.3.0)