Function to find complete word, but independent of position in string

Asked

Viewed 63 times

4

I’m having trouble using the str_detect to capture part of a text.

I need the str_detect take only the word "garlic", but regardless of her position in the string. Ex: "Brazilian garlic", "Brazilian garlic producers" or "garlic manufacturers".

Example:

str_detect(c("produção e trabalho","fabricante de alho",
             "alho brasileiro","produtores de alho brasileiro"),
             paste(c("carro", "futebol", 
              "^|[[:space:]]alho[[:space:]]|$"),collapse = '|'))

In this example, the str_detect is taking the words "work" and "garlic".

--

It is possible to solve with regex or another function?

I will use this logic for many words in a vector.

1 answer

4


You can use \b or \<\> to limit the beginning and end of a word:

grep('\\balho\\b', c("produção e trabalho","fabricante de alho", "alho brasileiro","tem alho aqui"), value = TRUE)
grep('\\<alho\\>', c("produção e trabalho","fabricante de alho", "alho brasileiro","tem alho aqui"), value = TRUE)

SOURCE: https://stackoverflow.com/a/7227999/6532002

  • Excellent! With \\b was show!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.