2

Is it possible to parse a vector of character strings to an alternation element in a regular expression? For example:

pattern <- "^This\\s(*alternation element*)\\srocks\\."
Animals <- c("cow","dog","cat")

So if I would then parse "Animals" to the regular expression it would result in:

pattern <- "^This\\s(*cow|dog|cat*)\\srocks\\."

It should basically work like or1() from the rebus package.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
MtH
  • 43
  • 5

2 Answers2

2

You could use paste0 to generate your regex :

paste0('^This\\s(', paste0(Animals, collapse = "|"), ')\\ssrocks\\.')
#[1] "^This\\s(cow|dog|cat)\\ssrocks\\."

Note than in R, you need to use double backslash (\\).

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

We can use sprintf

sprintf("^Thi\\s(%s)\\ssrocks\\.", paste(Animals, collapse="|"))
#[1] "^Thi\\s(cow|dog|cat)\\ssrocks\\."
akrun
  • 874,273
  • 37
  • 540
  • 662