Search code examples
rstringi

How do I extract a word, that is contained in a group/list of words, from a string?


From a character vector of strings

x <- c("Point to Point Movement, Route/Network Building",                                                                       
       "Betting/Wagering, Dice Rolling, Roll / Spin and Move",
       "Hand Management, Take That")

extract a word if it is contained in

p <- c("Route","Dice")

otherwise NA. The resulting output would be "Route" from x[1], "Dice" from x[2], and NA from x[3].


Solution

  • paste the words as a single string and use that in str_extract

    library(stringr)
    str_extract(x, str_c(p, collapse="|"))
    [1] "Route" "Dice"  NA