Often, we want the part of a string that comes before or after a given pattern.

library(strex)
#> Loading required package: stringr

Before

str_before_nth() gives you the part of a string before the nth appearance of a pattern. It has the friends str_before_first() and str_before_last().

string <- "ab..cd..de..fg..h"
str_before_first(string, "e")
#> [1] "ab..cd..d"
str_before_nth(string, "\\.", 3)
#> [1] "ab..cd"
str_before_last(string, "\\.")
#> [1] "ab..cd..de..fg."
str_before_nth(string, ".", -3)
#> [1] "ab..cd..de..fg"
str_before_nth(rep(string, 2), fixed("."), -3)
#> [1] "ab..cd..de." "ab..cd..de."

After

str_after_nth() gives you the part of a string after the nth appearance of a pattern. It has the friends str_after_first() and str_after_last().

string <- "ab..cd..de..fg..h"
str_after_first(string, "e")
#> [1] "..fg..h"
str_after_nth(string, "\\.", 3)
#> [1] ".de..fg..h"
str_after_last(string, "\\.")
#> [1] "h"
str_after_nth(string, ".", -3)
#> [1] ".h"
str_after_nth(rep(string, 2), fixed("."), -3)
#> [1] "fg..h" "fg..h"

A more concrete example

string <- "James did the cooking, Harry did the cleaning."

Let’s write a function to figure out which task each of the lads did.

library(magrittr)
get_task <- function(string, name) {
  str_c(name, " did the ") %>%
    str_after_first(string, .) %>%
    str_before_first("[\\.,]")
}
get_task(string, "James")
#> [1] "cooking"
get_task(string, "Harry")
#> [1] "cleaning"

get_task() would have been more difficult to write without str_after_first() and str_before_first().