Regular expression to search for R code in Sweave expression

I have some sweave expressions contained in the text in some .Rnw files. The paragraph below contains two sweave expressions. What regular expression can be used to search for R-code in each expression. Therefore, the regular expression should be able to find mean(mtcars$mpg) and / or summary(lm(mpg ~ hp + drat, mtcars))

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \ Sexpr {average (mtcars $ mpg)}. Ut enim ad minim veniam, quis nostrud, carrying out work carried out in accordance with needs. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat \ Sexpr {summary (lm (mpg ~ hp + drat, mtcars))} restless, ignited in culpa qui officia deserunt mollit anim id est laborum.

+6
source share
1 answer

The regular expression will be (?<=\\Sexpr{).+?(?=})

  • (?<=\\Sexpr{) part - positive lookbehind
  • (?=}) is a positive look
  • .+? It will be lazy to match everything that is between two viewpoints.

Read more here. http://www.regular-expressions.info/lookaround.html

eg. in R (since you marked R)

 txt <- 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \\Sexpr{mean(mtcars$mpg)}. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat \\Sexpr{summary(lm(mpg ~ hp + drat, mtcars))} non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' regmatches(txt, gregexpr('(?<=\\Sexpr{).+?(?=})', txt, perl=T)) ## [[1]] ## [1] "mean(mtcars$mpg)" "summary(lm(mpg ~ hp + drat, mtcars))" 
+5
source

All Articles