stringr::str_detect()
str_detect(string, pattern, regex = TRUE) Returns:
logical · Updated March 16, 2026 · Tidyverse stringr string pattern regex tidyverse
The str_detect() function from stringr detects whether a pattern exists within a string. It returns a logical vector indicating which strings contain the match, making it useful for filtering, conditional operations, and subsetting string data.
Syntax
str_detect(string, pattern, regex = TRUE)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
string | character | Required | A character vector to search |
pattern | pattern | Required | A pattern to look for (regex, fixed, or coll) |
regex | logical | TRUE | If TRUE, pattern is interpreted as a regular expression |
Examples
Basic usage
library(stringr)
# Detect a simple substring
strings <- c("apple", "banana", "cherry", "date")
str_detect(strings, "a")
# [1] TRUE TRUE FALSE TRUE
Using with dplyr filter
library(dplyr)
fruits <- data.frame(
name = c("apple", "banana", "cherry", "date", "apricot"),
color = c("red", "yellow", "red", "brown", "orange")
)
# Filter rows where name contains "a"
fruits %>% filter(str_detect(name, "a"))
# name color
# 1 apple red
# 2 banana yellow
# 3 apricot orange
Regex patterns
# Detect strings starting with "a"
str_detect(c("apple", "banana", "apricot"), "^a")
# [1] TRUE FALSE TRUE
# Detect strings ending with "e"
str_detect(c("apple", "banana", "cherry"), "e$")
# [1] TRUE FALSE TRUE
# Detect strings containing any digit
str_detect(c("abc123", "def", "xyz789"), "\\\\d")
# [1] TRUE FALSE TRUE
Case-insensitive matching
# Default is case-sensitive
str_detect("Apple", "apple")
# [1] FALSE
# Use regex with (?i) for case-insensitive
str_detect("Apple", "(?i)apple")
# [1] TRUE
# Or use fixed() for exact matching
str_detect("Apple", fixed("apple", ignore_case = TRUE))
# [1] TRUE
Detecting multiple patterns
# Detect any of multiple patterns using |
str_detect(c("cat", "dog", "bat"), "cat|dog")
# [1] TRUE TRUE FALSE
Common Patterns
- With dplyr::mutate: Add a column indicating pattern match
- With dplyr::filter: Subset rows based on string content
- With sum(): Count matching strings
- With which(): Get indices of matching strings
Combined with mutate
library(dplyr)
df <- data.frame(
email = c("user1@example.com", "invalid", "user2@test.org", "another.invalid")
)
df \%>\%
mutate(
is_valid_email = str_detect(email, "@.*\\\\.")
)
# email is_valid_email
# 1 user1@example.com TRUE
# 2 invalid FALSE
# 3 user2@test.org TRUE
# 4 another.invalid FALSE
Counting matches
strings <- c("apple", "banana", "cherry", "date", "apricot")
# Count how many strings contain "a"
sum(str_detect(strings, "a"))
# [1] 4