Search code examples
rregexalternation

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


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.


Solution

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