Question

I have some sweave expressions contained among text in some .Rnw files. The paragraph below contains two sweave expressions. What regular expression can I use to find the R code in each expression. So 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{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.

Was it helpful?

Solution

The regex would be (?<=\\Sexpr{).+?(?=})

  • (?<=\\Sexpr{) part is positive lookbehind
  • (?=}) is positive lookahead
  • .+? will match everything between above two lookarounds lazily.

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

E.g. in R (since you tagged 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))"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top