Use grepl to search either of multiple substrings in a text

You could paste the genres together with an "or" | separator and run that through grepl as a single regular expression.

x <- c("Action", "Adventure", "Animation", ...)
grepl(paste(x, collapse = "|"), my_text)

Here's an example.

x <- c("Action", "Adventure", "Animation")
my_text <- c("This one has Animation.", "This has none.", "Here is Adventure.")
grepl(paste(x, collapse = "|"), my_text)
# [1]  TRUE FALSE  TRUE

You can cycle through a list or vector of genres, as below:

genres <- c("Action",...,"Western")
sapply(genres, function(x) grepl(x, my_text))

To answer your question, if you just want to know if any element of the result is TRUE you can use the any() function.

any(sapply(genres, function(x) grepl(x, my_text)))

Quite simply, if any element of is TRUE, any will return TRUE.

Tags:

Regex

R

Grepl