← All languages
R function of the day
Random

grep

Search for pattern matches in a character vector.

Description

The grep() function searches for matches to a pattern within each element of a character vector. By default, it returns the indices of matching elements. Setting value = TRUE returns the matching elements themselves instead.

grepl() is a related function that returns a logical vector indicating which elements match. Both support regular expressions and fixed string matching.

Arguments

NameDescriptionOptional
pattern A character string containing a regular expression to match. No
x A character vector to search in. No
value Logical. If TRUE, return the matching elements instead of indices. Defaults to FALSE. Yes
ignore.case Logical. If TRUE, pattern matching is case-insensitive. Defaults to FALSE. Yes

Example

fruits <- c("apple", "banana", "cherry", "apricot")
grep("ap", fruits)                  # 1 4
grep("ap", fruits, value = TRUE)    # "apple" "apricot"
grepl("an", fruits)                 # FALSE TRUE FALSE FALSE

Reference