How to use a list of vectors in alternation (regular expressions)

83 views Asked by At

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.

2

There are 2 answers

0
Ronak Shah On BEST ANSWER

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 (\\).

0
akrun On

We can use sprintf

sprintf("^Thi\\s(%s)\\ssrocks\\.", paste(Animals, collapse="|"))
#[1] "^Thi\\s(cow|dog|cat)\\ssrocks\\."