str_detect

The function stringr::str_detect() detects the presence of a pattern/regular expression within each element of a string vector. It returns a logical vector with TRUE for matches and FALSE otherwise.

Tidyverse reference page

String vector

Prior to using the function create a vector of strings.

#Create vector of strings
vec <- c("Rose", "Thistle", "Leek", "Shamrock")
#View vector
vec
[1] "Rose"     "Thistle"  "Leek"     "Shamrock"

Basic searches

You can specify a string pattern to be used for detection.

#Detect the letter a
vec |> stringr::str_detect("a")
[1] FALSE FALSE FALSE  TRUE

The function is case-sensitive. “R” will detect “Rose” but not “shamrock”.

#Detect the letter R
vec |> stringr::str_detect("R")
[1]  TRUE FALSE FALSE FALSE

You can use various regular expressions.

#Detect the strings ending with k 
vec |> stringr::str_detect("k$")
[1] FALSE FALSE  TRUE  TRUE
#Detect the letter R or r
vec |> stringr::str_detect("[Rr]")
[1]  TRUE FALSE FALSE  TRUE
#Detect letter s that has a vowel before it
vec |> stringr::str_detect("[aeiou]s")
[1]  TRUE  TRUE FALSE FALSE

Negate

You carry out an inverted search (i.e. it returns FALSE if it does match) with the option negate=TRUE.

#Invert detect letter s that has a vowel before it
vec |> stringr::str_detect("[aeiou]s", negate=TRUE)
[1] FALSE FALSE  TRUE  TRUE