str_remove_first()
removes the first occurrence of a pattern in each string.
str_remove_all()
removes all occurrences of a pattern in each string.
Usage
str_remove_first(strings, pattern, fixed = FALSE)
str_remove_all(strings, pattern, fixed = FALSE)
str_remove_nth(strings, pattern, n, fixed = FALSE)
str_remove_last(strings, pattern, 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.- fixed
Logical; whether
pattern
should be matched exactly, treating regex special characters as regular string characters. DefaultFALSE
.- n
(
str_remove_nth
only) Integer, the nth occurrence of the pattern to replace. Negative values count back from the end.
Value
A character vector of the same length as strings
, with the specified pattern removed.
For str_remove_first()
, only the first occurrence of the pattern in each string is removed.
For str_remove_all()
, all occurrences of the pattern in each string are removed.
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/
See also
str_replace_all()
and family for replacing patterns with specific text.
str_remove
functions are equivalent to calling those with replacement = ""
Examples
string <- "carrot, car park, cable car"
str_remove_first(string, "car")
#> [1] "rot, car park, cable car"
str_remove_nth(string, "car", 2)
#> [1] "carrot, park, cable car"
str_remove_last(string, "car")
#> [1] "carrot, car park, cable "
str_remove_all(string, "car")
#> [1] "rot, park, cable "