Learn R Programming

stringr (version 1.1.0)

str_replace: Replace matched patterns in a string.

Description

Vectorised over string, pattern and replacement.

Usage

str_replace(string, pattern, replacement)
str_replace_all(string, pattern, replacement)

Arguments

string
Input vector. Either a character vector, or something coercible to one.
pattern, replacement
Supply separate pattern and replacement strings to vectorise over the patterns. References of the form \1, \2 will be replaced with the contents of the respective matched group (created by ()) within the pattern.

For str_replace_all only, you can perform multiple patterns and replacements to each string, by passing a named character to pattern.

Value

A character vector.

See Also

str_replace_na to turn missing values into "NA"; stri_replace for the underlying implementation.

Examples

Run this code
fruits <- c("one apple", "two pears", "three bananas")
str_replace(fruits, "[aeiou]", "-")
str_replace_all(fruits, "[aeiou]", "-")

str_replace(fruits, "([aeiou])", "")
str_replace(fruits, "([aeiou])", "\\1\\1")
str_replace(fruits, "[aeiou]", c("1", "2", "3"))
str_replace(fruits, c("a", "e", "i"), "-")

fruits <- c("one apple", "two pears", "three bananas")
str_replace(fruits, "[aeiou]", "-")
str_replace_all(fruits, "[aeiou]", "-")

str_replace_all(fruits, "([aeiou])", "")
str_replace_all(fruits, "([aeiou])", "\\1\\1")
str_replace_all(fruits, "[aeiou]", c("1", "2", "3"))
str_replace_all(fruits, c("a", "e", "i"), "-")

# If you want to apply multiple patterns and replacements to the same
# string, pass a named version to pattern.
str_replace_all(str_c(fruits, collapse = "---"),
 c("one" = 1, "two" = 2, "three" = 3))

Run the code above in your browser using DataLab