grep()

grep(pattern, x, value = FALSE, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE, invert = FALSE)
Returns: integer · Updated March 13, 2026 · String Functions
string pattern-matching regex base

grep() searches for matches to a pattern in a character vector and returns the indices of elements that match.

Syntax

grep(pattern, x, value = FALSE, ignore.case = FALSE, 
     perl = FALSE, fixed = FALSE, useBytes = FALSE, invert = FALSE)

Parameters

ParameterTypeDefaultDescription
patterncharacterA regular expression pattern to match
xcharacterA character vector to search in
valuelogicalFALSEIf TRUE, return the matching strings instead of indices
ignore.caselogicalFALSEIf TRUE, ignore case when matching
perllogicalFALSEIf TRUE, use Perl-compatible regular expressions
fixedlogicalFALSEIf TRUE, treat pattern as a literal string (faster)
useByteslogicalFALSEIf TRUE, match byte-by-byte rather than character-by-character
invertlogicalFALSEIf TRUE, return indices of elements that do NOT match

Examples

Basic usage

fruits <- c("apple", "banana", "cherry", "date", "elderberry")

grep("a", fruits)
# [1] 1 2 4

Using value = TRUE

grep("a", fruits, value = TRUE)
# [1] "apple"    "banana"   "date"

Case-insensitive matching

colors <- c("Red", "GREEN", "blue", "YELLOW")

grep("red", colors, ignore.case = TRUE, value = TRUE)
# [1] "Red"   "GREEN"

Fixed string matching (faster)

emails <- c("user@example.com", "test@domain.org", "invalid")

grep("@", emails, fixed = TRUE, value = TRUE)
# [1] "user@example.com" "test@domain.org"

Invert to find non-matches

grep("a", fruits, invert = TRUE, value = TRUE)
# [1] "cherry"    "elderberry"

Common Patterns

Counting matches

length(grep("pattern", strings))

Filtering data frames

df[grep("pattern", df$column), ]

Multiple patterns (OR logic)

grep("apple|orange", fruits, value = TRUE)

See Also