R/helpers-define-run.R

Defines functions extract_between

Documented in extract_between

#' Extract a portion of a string between two patterns
#'
#' If a string has more than one match, this will only return the first one.
#'
#' @param full_string The full character string to extract from.
#' @param after_string A pattern specifying the string should be extracted after this.
#' @param before_string A pattern specifying the string should be extracted before this.
#' @param trim_spaces logical T/F, if there are any spaces within the extracted
#'   string, they will be removed. Default is TRUE.
#' @return A string
#' @keywords internal
#'
extract_between <- function(full_string, after_string, before_string, trim_spaces = TRUE) {

  reg_pattern <- paste0("(?<=", after_string, ").*(?=", before_string, ")")

  out <- regmatches(full_string, gregexpr(pattern = reg_pattern,
                                          text = full_string,
                                          perl = T))[[1]]

  if (trim_spaces) {
    out <- trimws(out)
  }

  return(out)
}
jdtrat/taskdesignr documentation built on Feb. 4, 2021, 9:48 p.m.