Learn R Programming

stringr (version 1.5.1)

str_replace: Replace matches with new text

Description

str_replace() replaces the first match; str_replace_all() replaces all matches.

Usage

str_replace(string, pattern, replacement)

str_replace_all(string, pattern, replacement)

Value

A character vector the same length as string/pattern/replacement.

Arguments

string

Input vector. Either a character vector, or something coercible to one.

pattern

Pattern to look for.

The default interpretation is a regular expression, as described in stringi::about_search_regex. Control options with regex().

For str_replace_all() this can also be a named vector (c(pattern1 = replacement1)), in order to perform multiple replacements in each element of string.

Match a fixed string (i.e. by comparing only bytes), using fixed(). This is fast, but approximate. Generally, for matching human text, you'll want coll() which respects character matching rules for the specified locale.

replacement

The replacement value, usually a single string, but it can be the a vector the same length as string or pattern. References of the form \1, \2, etc will be replaced with the contents of the respective matched group (created by ()).

Alternatively, supply a function, which will be called once for each match (from right to left) and its return value will be used to replace the match.

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_all(fruits, "[aeiou]", toupper)
str_replace_all(fruits, "b", NA_character_)

str_replace(fruits, "([aeiou])", "")
str_replace(fruits, "([aeiou])", "\\1\\1")

# Note that str_replace() is vectorised along text, pattern, and replacement
str_replace(fruits, "[aeiou]", c("1", "2", "3"))
str_replace(fruits, c("a", "e", "i"), "-")

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

# Use a function for more sophisticated replacement. This example
# replaces colour names with their hex values.
colours <- str_c("\\b", colors(), "\\b", collapse="|")
col2hex <- function(col) {
  rgb <- col2rgb(col)
  rgb(rgb["red", ], rgb["green", ], rgb["blue", ], max = 255)
}

x <- c(
  "Roses are red, violets are blue",
  "My favourite colour is green"
)
str_replace_all(x, colours, col2hex)

Run the code above in your browser using DataLab