Q:

Extract array of objects from string in R

Suppose i have the following string:
str <- "var x = 1; var b = [{a:c, d:f}, {aa:cc, dd:ff}]; var notOfInterest = {cc:r, dd:w}"

I would like to extract all objects within that array "[{...}, {...}]" not single objects "{...}" (in this example: var notOfInterest).
Desired Output:
> list(c("{a:c, d:f}", "{aa:cc, dd:ff}"))
[[1]]
[1] "{a:c, d:f}"     "{aa:cc, dd:ff}"

What i tried:
Building on this Question/answer: find json in string with R i tried to add brackets. 
I tried with adjusted Input string:
  str2 <- "var x = 1; var b = [{a:c, d:f}]; var notOfInterest = {cc:r, dd:w}"
(just for Debugging purposes. str is still my target string). Even that step doesnt work. After that i would have to add an optional comma and allow the object to appear multiple times.
gregexpr(
  pattern = "[\\{(?:[^{}]|(?R))*?\\}]",
  perl = TRUE,
  text = str
) %>%
  regmatches(x = str)

I tried with "fixed = TRUE" Parameter, escaping the brackets and some more options which i am very happy to post the code for, but
i guess the question will get too long.

A:

You can do that using stringr package like that;
library(stringr)
str <- "var x = 1; var b = [{a:c, d:f}, {aa:cc, dd:ff}]; var notOfInterest = {cc:r, dd:w}"

To match first occurrence only and result will be vector
str_extract(str, "(?<=\\[).+?(?=\\])")
# [1] "{a:c, d:f}, {aa:cc, dd:ff}"

To get all occurrences and result will be a list 
str_extract_all(str, "(?<=\\[).+?(?=\\])")
# [[1]]
# [1] "{a:c, d:f}, {aa:cc, dd:ff}"

