
Extract text before or after nth occurrence of pattern.
Source: R/after.R, R/before.R
before-and-after.RdExtract the part of a string which is before or after the nth occurrence of
a specified pattern, vectorized over the string.
Usage
str_after_nth(string, pattern, n)
str_after_first(string, pattern)
str_after_last(string, pattern)
str_before_nth(string, pattern, n)
str_before_first(string, pattern)
str_before_last(string, pattern)Arguments
- string
A character vector.
- pattern
The pattern to look for.
The default interpretation is a regular expression, as described in stringi::about_search_regex.
To match a without regular expression (i.e. as a human would), use coll(). For details see
stringr::regex().- n
A vector of integerish values. Must be either length 1 or have length equal to the length of
string. Negative indices count from the back: whilen = 1andn = 2correspond to first and second,n = -1andn = -2correspond to last and second-last.n = 0will returnNA.
Details
str_after_first(...)is juststr_after_nth(..., n = 1).str_after_last(...)is juststr_after_nth(..., n = -1).str_before_first(...)is juststr_before_nth(..., n = 1).str_before_last(...)is juststr_before_nth(..., n = -1).
See also
Other bisectors:
str_before_last_dot()
Examples
string <- "abxxcdxxdexxfgxxh"
str_after_nth(string, "xx", 3)
#> [1] "fgxxh"
str_before_nth(string, "e", 1:2)
#> [1] "abxxcdxxd" NA
str_before_nth(string, "xx", -3)
#> [1] "abxxcd"
str_before_nth(string, ".", -3)
#> [1] "abxxcdxxdexxfg"
str_before_nth(rep(string, 2), "..x", -3)
#> [1] "abxx" "abxx"
str_before_first(string, "d")
#> [1] "abxxc"
str_before_last(string, "x")
#> [1] "abxxcdxxdexxfgx"
string <- c("abc", "xyz.zyx")
str_after_first(string, ".") # using regex
#> [1] "bc" "yz.zyx"
str_after_first(string, coll(".")) # using human matching
#> [1] NA "zyx"
str_after_last(c("xy", "xz"), "x")
#> [1] "y" "z"