Regex let's you use \\b
for word boundaries:
grepl("\\bred\\b|\\bgreen\\b", x, ignore.case = TRUE)
# [1] TRUE FALSE TRUE FALSE
This will work well if you want to match the words within longer strings:
grepl("\\bred\\b|\\bgreen\\b",
c("I want to match red", "But not Fred",
"Green yes please", "ignore wintergreen"),
ignore.case=TRUE)
# [1] TRUE FALSE TRUE FALSE
However, if you're doing whole string matching, regex is overkill, equality matching will be much faster:
tolower(x) %in% c("red", "green")
[1] TRUE FALSE TRUE FALSE
If we start with patterns = c("red|green")
we can get to either of the needed cases above:
## use this with `%in%`
individual_words = unlist(strsplit(patterns, split = "\\|"))
## or paste on the word boundaries for regex
word_boundary_patterns = paste0("\\b", individual_words, "\\b", collapse = "|")