sub()
sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE) Returns:
character · Updated March 13, 2026 · String Functions string pattern replace regex
sub() is a base R function for finding and replacing text patterns in character strings. It replaces only the first occurrence of a pattern in each element. Both support regular expressions, fixed matching, and case-insensitive options.
Syntax
sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
pattern | character | — | A pattern to search for (regex, literal string, or fixed if fixed = TRUE) |
replacement | character | — | The replacement string. Use backreferences (\1, \2, etc.) with capture groups in regex mode |
x | character | — | A character vector where patterns will be searched |
ignore.case | logical | FALSE | If TRUE, the search is case-insensitive |
perl | logical | FALSE | If TRUE, use Perl-compatible regular expressions |
fixed | logical | FALSE | If TRUE, treat pattern as a literal string rather than regex |
Examples
Basic replacement (first match only)
text <- "The cat sat on the cat mat"
sub("cat", "dog", text)
# [1] "The dog sat on the cat mat"
phone <- "555-123-4567"
sub("-", ":", phone)
# [1] "555:123-4567"
Case-insensitive matching
text <- "R is GREAT and r is great"
sub("r", "X", text, ignore.case = TRUE)
# [1] "X is GREAT and r is great"
Using backreferences
names <- c("John Doe", "Jane Smith", "Bob Wilson")
sub("(\\w+) (\\w+)", "\\2, \\1", names)
# [1] "Doe, John" "Jane Smith" "Bob Wilson"
# Note: only the first name is transformed
Fixed matching (literal strings)
filename <- "file.old.old"
sub(".old", ".new", filename, fixed = TRUE)
# [1] "file.new.old"
Common Patterns
Replace first instance in formatted text
text <- "Price: $100, Discount: 10%"
sub("\\$", "USD ", text)
# [1] "Price: USD 100, Discount: 10%"