Vectorised over string, pattern and replacement.

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

Pattern to look for.

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

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

A character vector of replacements. Should be either length one, or 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 ()).

To perform multiple replacements in each element of string, pass a named vector (c(pattern1 = replacement1)) to str_replace_all. Alternatively, pass a function to replacement: it will be called once for each match and its return value will be used to replace the match.

To replace the complete string with NA, use replacement = NA_character_.

Value

A character vector.

See also

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

Examples

fruits <- c("one apple", "two pears", "three bananas") str_replace(fruits, "[aeiou]", "-")
#> [1] "-ne apple" "tw- pears" "thr-e bananas"
str_replace_all(fruits, "[aeiou]", "-")
#> [1] "-n- -ppl-" "tw- p--rs" "thr-- b-n-n-s"
str_replace_all(fruits, "[aeiou]", toupper)
#> [1] "OnE ApplE" "twO pEArs" "thrEE bAnAnAs"
str_replace_all(fruits, "b", NA_character_)
#> [1] "one apple" "two pears" NA
str_replace(fruits, "([aeiou])", "")
#> [1] "ne apple" "tw pears" "thre bananas"
str_replace(fruits, "([aeiou])", "\\1\\1")
#> [1] "oone apple" "twoo pears" "threee bananas"
str_replace(fruits, "[aeiou]", c("1", "2", "3"))
#> [1] "1ne apple" "tw2 pears" "thr3e bananas"
str_replace(fruits, c("a", "e", "i"), "-")
#> [1] "one -pple" "two p-ars" "three bananas"
# 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"))
#> [1] "1 apple---2 pears---3 bananas"
# 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)
#> [1] "Roses are #FF0000, violets are #0000FF" #> [2] "My favourite colour is #00FF00"