stringr::str_replace()
str_replace(string, pattern, replacement) The str_replace() function from stringr replaces the first occurrence of a pattern in a string. For replacing all occurrences, use str_replace_all(). These functions are essential for text cleaning, formatting, and transformation tasks.
Syntax
str_replace(string, pattern, replacement)
str_replace_all(string, pattern, replacement)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
string | character | Required | A character vector to modify |
pattern | pattern | Required | A pattern to find (regex, fixed, or coll) |
replacement | character | Required | The replacement string |
Examples
Basic usage
library(stringr)
# Replace first occurrence
str_replace("hello world", "world", "R")
# [1] "hello R"
# Replace all occurrences
str_replace_all("babababab", "b", "a")
# [1] "aaaaa"
The key difference between str_replace() and str_replace_all() is scope: the former stops after the first match while the latter processes every match in the string. When you need to clean an entire dataset column by replacing all instances of a character or substring, str_replace_all() is the appropriate function to call.
Using with dplyr mutate
library(dplyr)
df <- data.frame(
name = c("john_smith", "jane_doe", "bob_jones")
)
# Replace underscores with spaces
df %>% mutate(name_clean = str_replace_all(name, "_", " "))
# name name_clean
# 1 john_smith john smith
# 2 jane_doe jane doe
# 3 bob_jones bob jones
Using str_replace_all() inside dplyr::mutate() lets you clean or transform a text column in place within a data pipeline. This pattern is especially useful when preparing imported data where separators like underscores or dashes need to be converted to spaces for display.
Regex patterns
# Replace digits
str_replace_all("order123", "\\d+", "N")
# [1] "orderN"
# Replace multiple spaces with single space
str_replace_all("too many spaces", "\\s+", " ")
# [1] "too many spaces"
# Replace at word boundaries
str_replace_all("the cat and the dog", "\\bthe\\b", "a")
# [1] "a cat and a dog"
Regular expressions give you precise control over what gets replaced. The \\d+ pattern matches one or more digits, \\s+ matches one or more whitespace characters, and \\b anchors the match to word boundaries so that partial word matches are avoided.
Capture groups
# Use parentheses to capture groups, reference with \\1, \\2, etc.
str_replace("2026-03-16", "(\\d{4})-(\\d{2})-(\\d{2})", "\\3/\\2/\\1")
# [1] "16/03/2026"
# Swap first and last names
str_replace("Doe, John", "(\\w+), (\\w+)", "\\2 \\1")
# [1] "John Doe"
Capture groups, defined by parentheses in the pattern, let you extract specific parts of the matched text and rearrange them in the replacement string. Backreferences like \\1 refer to the first captured group, \\2 to the second, and so on, making date reformatting and name swapping straightforward in a single function call.
Case conversion
# Convert to lowercase
str_replace("HELLO", "HELLO", "hello")
# [1] "hello"
# Toggle case (upper to lower, lower to upper)
str_replace("Hello World", "([a-z])([A-Z])", "\\1\\2")
# This requires more complex patterns
For simple case changes, replacing the entire string is more straightforward than trying to construct a regex that toggles individual character cases. The str_to_lower() and str_to_upper() functions from stringr are better suited for wholesale case conversion of entire strings rather than character-by-character manipulation.
HTML cleaning
# Remove HTML tags
str_replace_all("<p>Hello</p>", "<[^>]+>", "")
# [1] "Hello"
# Replace URLs with placeholder
str_replace_all("Visit https://example.com today",
"https?://[^\\s]+", "[URL]")
# [1] "Visit [URL] today"
Stripping HTML tags or replacing URLs with placeholders is a common text-cleaning task in web scraping and data preparation workflows. The pattern <[^>]+> matches any HTML tag by looking for angle brackets containing one or more characters that are not a closing angle bracket.
Backreferences and special cases
Backreferences with named groups
# Named capture groups
str_replace("john@example.com",
"(?<user>[^@]+)@(?<domain>.+)",
"\\<domain>/\\<user>")
# [1] "example.com/john"
Named capture groups, written as (?<name>...), make backreferences more readable than numbered groups. When the replacement string references a named group with \\<name>, the intent of the code becomes clearer, which is especially valuable in longer or collaborative data-cleaning scripts.
Special replacement functions
# Use a function as replacement for dynamic substitution
str_replace_all(c("apple", "banana", "cherry"),
"^[a-z]",
toupper)
# [1] "Apple" "Banana" "Cherry"
# Use with dplyr
df <- data.frame(
text = c("cat", "dog", "bird")
)
df %>% mutate(
upper = str_replace_all(text, "^[a-z]", toupper)
)
# text upper
# 1 cat Cat
# 2 dog Dog
# 3 bird Bird
Instead of a static replacement string, you can pass a function like toupper or tolower as the replacement argument. The function is applied to each matched substring, enabling dynamic transformations that would otherwise require multiple separate replacement calls or complex regex patterns.
Common use cases
Data cleaning
# Clean phone numbers
str_replace_all("+1-555-123-4567", "[^0-9]", "")
# [1] "15551234567"
# Normalize whitespace
str_replace_all(" hello world ", "\\s+", " ")
# [1] " hello world "
Removing all non-numeric characters from a phone number is a typical data-cleaning operation that normalises free-form user input into a consistent format. The negated character class [^0-9] matches everything except digits and strips it away in one pass with str_replace_all().
Text normalization
# Standardize dates
str_replace_all(c("03/16/2026", "2026-03-16", "16.03.2026"),
"\\d+", "DD")
# [1] "DD/DD/DDDD" "DD-DD-DD" "DD.DD.DDDD"
Standardising date formats across a dataset is another common use of str_replace_all(). By replacing all digit sequences with a placeholder, you can quickly visualise which format each date string follows before deciding on a uniform conversion strategy for the entire column.
String transformation
# Convert snake_case to camelCase
str_replace_all("hello_world_test", "_([a-z])", "\\U\\1")
# [1] "helloWorldTest"
# Remove prefixes
str_replace("package_function", "^[^_]+_", "")
# [1] "function"
stringr::str_replace() in practice
str_replace() replaces the first occurrence of a pattern; str_replace_all() replaces all occurrences. They are the stringr equivalents of base R’s sub() and gsub(). The stringr versions use PCRE regex by default, while base R’s functions use TRE regex unless perl = TRUE is specified.
Backreferences in the replacement use \\1 for the first capture group: str_replace(x, "(\\w+) (\\w+)", "\\2 \\1") swaps the first two words. Named capture groups use \\{name}.
str_replace_all() also accepts a named character vector as replacement, where names are patterns and values are replacements. str_replace_all(x, c("foo" = "bar", "baz" = "qux")) applies multiple replacements in sequence. This avoids chaining multiple str_replace_all() calls and is more efficient for batch substitution.
Use fixed("literal_string") when the pattern should match literally rather than as a regex: str_replace(x, fixed("(1+1)"), "2") replaces the literal string "(1+1)". Without fixed(), the parentheses and plus would be interpreted as regex metacharacters.
str_replace() replaces only the first match per string. Use str_replace_all() to replace every match. Backreferences in the replacement string use \1, \2 syntax. Captured groups in the pattern can be referenced in the replacement: str_replace(x, "(\w+)-(\w+)", "\2-\1") swaps two hyphen-separated words. For literal replacement without regex, wrap the pattern in fixed().
Replacement string syntax
The replacement string in str_replace() and str_replace_all() supports backreferences when the pattern contains capture groups. \1 refers to the first capture group, \2 to the second. This enables transformations where parts of the matched text are rearranged or reused in the replacement. For example, swapping “first last” to “last, first” uses two capture groups and a replacement string that references them in reverse order.
For literal replacement strings that might contain backslashes, use fixed() for the pattern or escape any backslashes in the replacement. The replacement string is interpreted as a replacement template by the regex engine, so special characters in the replacement need escaping just as they do in patterns.
See also
- stringr::str_detect(), Detect patterns in strings
- stringr::str_extract(), Extract matching patterns from strings
- stringr::str_sub(), Extract or replace substrings by position