Test If a String Contains a Specified Pattern

str_detect() returns a logical vector, with TRUE for each string element that contains a match of the specified pattern, and FALSE for each string element that doesn’t has such a match.

library(stringr)
fruit <- c("apple", "banana", "pear", "kiwi")# test if each element contains letter estr_detect(fruit, pattern = "e")

Output:

[1] TRUE FALSE TRUE FALSE

The argument negate = T reverses the logical values: it returns matched string elements as FALSE, and mismatched ones as TRUE.

str_detect(c(fruit), pattern = "e", negate = T)

Output:

[1] FALSE TRUE FALSE TRUE

The above code is equivalent to the following line.

! str_detect(fruit, pattern = "e", negate = F) 

NA elements in the input string will be returned as NA.

str_detect(c(NA, "apple", "bee"), pattern = "e")

Output:

[1] NA TRUE TRUE

🎁 Bonus skills !

str_starts() and str_ends() are special cases of str_detect() that only search the matched pattern at the very beginning or end of a string, respectively.

fruit <- c("apple", "lemon", "barley")str_starts(fruit, pattern = "le")

Output:

[1] FALSE TRUE FALSE
str_ends(fruit, pattern = "le")

Output:

[1] TRUE FALSE FALSE