Extract string between curly braces using str_extract_all

Viewed 120

I have the following code:

myFunction.R

myFunction({
  lorem <- "ipsum"
  ...
  print("dolor sit amet")
})

myFunction({
  consectetur <- "adipiscing elit"
  ...
  sed <- paste("do", "eiusmod")
})

...

In another R script, I would like to extract all myFunction calls. Right now the best that I came up with was:

library(stringr)
library(readtext)

script <- readtext('myFunction.R')[['text']]
matches <- str_extract_all(script, 'myFunction(.|\\n)*\\}\\)')[[1]]

But unfortunately, matches contain the first myFunction call until the end of the file. How can I improve the RegEx to match only each myFunction call?

1 Answers

You can use

str_extract_all(script, "(?ms)^myFunction\\(\\{.*?^\\}\\)$")

Details:

  • (?ms) - turn on multiline (m, makes ^ and $ match start and end of lines respectively) and dotall (s, makes . also match line break chars that it does not match by default) modes
  • ^ - start of a line
  • myFunction\\(\\{ - a literal myFunction({ text
  • .*? - any zero or more chars, as few as possible
  • ^ - start of a line
  • \}\) - a literal }) text
  • $ - end of a line.
Related