R/utils-rematch2.R

Defines functions re_match

# inlined from
# https://github.com/r-lib/rematch2/commit/aab858e3411810fa107d20db6f936c6b10cbdf3f
# EXCEPT I don't return a tibble

re_match <- function(text, pattern, perl = TRUE, ...) {

  check_string(pattern)
  text <- as.character(text)

  match <- regexpr(pattern, text, perl = perl, ...)

  start  <- as.vector(match)
  length <- attr(match, "match.length")
  end    <- start + length - 1L

  matchstr <- substring(text, start, end)
  matchstr[ start == -1 ] <- NA_character_

  res <- data.frame(
    stringsAsFactors = FALSE,
    .text = text,
    .match = matchstr
  )

  if (!is.null(attr(match, "capture.start"))) {

    gstart  <- attr(match, "capture.start")
    glength <- attr(match, "capture.length")
    gend    <- gstart + glength - 1L

    groupstr <- substring(text, gstart, gend)
    groupstr[ gstart == -1 ] <- NA_character_
    dim(groupstr) <- dim(gstart)

    res <- cbind(groupstr, res, stringsAsFactors = FALSE)
  }

  names(res) <- c(attr(match, "capture.names"), ".text", ".match")
  #class(res) <- c("tbl_df", "tbl", class(res))
  res
}
r-lib/usethis documentation built on March 20, 2024, 8:51 p.m.