Often, we want the part of a string that comes before or after a given pattern.
library(strex)
#> Loading required package: stringr
str_before_nth()
gives you the part of a string before
the n
th appearance of a pattern. It has the
friends str_before_first()
and
str_before_last()
.
<- "ab..cd..de..fg..h"
string 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."
str_after_nth()
gives you the part of a string after the
n
th appearance of a pattern. It has the friends
str_after_first()
and str_after_last()
.
<- "ab..cd..de..fg..h"
string 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"
<- "James did the cooking, Harry did the cleaning." string
Let’s write a function to figure out which task each of the lads did.
library(magrittr)
<- function(string, name) {
get_task 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()
.