Domnick Domnick - 24 days ago 6
R Question

Find the words in list of strings

I have

words <- c("word1", "word")
text <- c("this is word1", "this is word2", "this is word4")


If I use
sapply(words, grepl, text)
gives you answer in TRUE and FALSE,
instead how can I get the exact words that has matched
such that the answer would be

"this is word1"


I being new to R pardon for such silly question.
Any ideas are welcome.

Answer Source

One option would be to create word boundary and then use grep to avoid any partial matching of strings and with value = TRUE, it returns the string instead of the index

grep(paste0("\\b(", paste(words, collapse="|"), ")\\b"), text, value = TRUE)
#[1] "this is word1"