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
| Parameter | Type | Default | Description |
|---|---|---|---|
| pattern | character | — | A regular expression pattern to match |
| x | character | — | A character vector to search in |
| value | logical | FALSE | If TRUE, return the matching strings instead of indices |
| ignore.case | logical | FALSE | If TRUE, ignore case when matching |
| perl | logical | FALSE | If TRUE, use Perl-compatible regular expressions |
| fixed | logical | FALSE | If TRUE, treat pattern as a literal string (faster) |
| useBytes | logical | FALSE | If TRUE, match byte-by-byte rather than character-by-character |
| invert | logical | FALSE | If 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)