str_replace_first()
, str_replace_nth()
and str_replace_last()
:
Replace the specified pattern occurrence in each string.
str_replace_all()
Replace every pattern occurrence in each string.
Usage
str_replace_first(strings, pattern, replacement, fixed = FALSE)
str_replace_all(strings, pattern, replacement, fixed = FALSE)
str_replace_nth(strings, pattern, replacement, n, fixed = FALSE)
str_replace_last(strings, pattern, replacement, fixed = FALSE)
Arguments
- strings
A character vector, where each element of the vector is a character string.
- pattern
A single character string to be searched for in each element of
strings
. By default,pattern
is interpreted as a regular expression (regex). If thefixed
argument is set toTRUE
,pattern
will be treated as a literal string to be matched exactly.- replacement
A single string containing the text to replace the pattern with.
- fixed
Logical; whether
pattern
should be matched exactly, treating regex special characters as regular string characters. DefaultFALSE
.- n
(
str_replace_nth
only) Integer, the nth occurrence of the pattern to replace. Negative values count back from the end.
Value
str_replace_first()
, str_replace_nth()
and str_replace_last()
:
Returns an altered character vector of equal length to strings
,
with the first, nth and last pattern occurrence, respectively,
replaced by the replacement
text.
str_replace_all()
Returns an altered character vector of equal length to strings
,
with every match in each string replaced.
Details
These functions are built using the base R regular expression functions.
{suitestrings}
uses Perl-compatible Regular Expressions (PCRE).
This is achieved by setting perl = TRUE
in the underlying base functions.
See R's regexp documentation for info on the regex implementation.
For complete syntax details see https://www.pcre.org/current/doc/html/
Examples
strings <- c("banana", "banana banana", "no match here")
str_replace_first(strings, "na", "NA")
#> [1] "baNAna" "baNAna banana" "no match here"
str_replace_nth(strings, "na", "NA", 2)
#> [1] "banaNA" "banaNA banana" "no match here"
str_replace_last(strings, "na", "NA")
#> [1] "banaNA" "banana banaNA" "no match here"
str_replace_all(strings, "na", "NA")
#> [1] "baNANA" "baNANA baNANA" "no match here"