gsub()
gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE) Returns:
character · Updated March 13, 2026 · String Functions string pattern replace regex
gsub() is a base R function for finding and replacing text patterns in character strings. It replaces all occurrences of a pattern. Both support regular expressions, fixed matching, and case-insensitive options.
Syntax
gsub(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
text <- "The cat sat on the mat"
gsub("cat", "dog", text)
# [1] "The dog sat on the mat"
phone <- "Call me at 555-123-4567"
gsub("[0-9]", "", phone)
# [1] "Call me at ---"
filename <- "my report final.pdf"
gsub(" ", "_", filename)
# [1] "my_report_final.pdf"
Case-insensitive matching
text <- "R is GREAT and r is great"
gsub("r", "X", text, ignore.case = TRUE)
# [1] "X is GREAT and X is gXeat"
Using backreferences
names <- c("John Doe", "Jane Smith", "Bob Wilson")
gsub("(\\w+) (\\w+)", "\\2, \\1", names)
# [1] "Doe, John" "Smith, Jane" "Wilson, Bob"
phones <- c("555-123-4567", "987-654-3210")
gsub("([0-9]{3})-([0-9]{3})-([0-9]{4})", "(\\1) \\2-\\3", phones)
# [1] "(555) 123-4567" "(987) 654-3210"
Fixed matching (literal strings)
filename <- "report.txt.old"
gsub(".old", ".new", filename, fixed = TRUE)
# [1] "report.txt.new"
Common Patterns
Text cleaning
messy <- " hello world "
gsub("\\s+", " ", messy)
# [1] " hello world "
html <- "<p>Hello <b>world</b></p>"
gsub("<[^>]+>", "", html)
# [1] "Hello world"