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.