The hardware and bandwidth for this mirror is donated by dogado GmbH, the Webhosting and Full Service-Cloud Provider. Check out our Wordpress Tutorial.
If you wish to report a bug, or if you are interested in having us mirror your free-software or open-source project, please feel free to contact us at mirror[@]dogado.de.

Before and After

2024-10-01

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().

These binaries (installable software) and packages are in development.
They may not be fully stable and should be used with caution. We make no claims about them.
Health stats visible at Monitor.