🔍 An RStudio addin slash regex utility belt
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

132 satır
4.1KB

  1. #' @export
  2. run_regex <- function(
  3. text,
  4. pattern,
  5. ignore.case = FALSE,
  6. perl = FALSE,
  7. fixed = FALSE,
  8. useBytes = FALSE,
  9. invert = FALSE
  10. ) {
  11. m <- regexec(pattern, text, ignore.case, perl, fixed, useBytes)
  12. x <- purrr::map(purrr::set_names(m, text), function(mi) list('idx' = purrr::map2(mi, attr(mi, "match.length"), ~ if(.x[1] != -1) c(.x, .x + .y - 1L))))
  13. y <- purrr::map(purrr::set_names(text), ~ list(text = .))
  14. z <- purrr::map(purrr::set_names(regmatches(text, m), text), ~ list(m = .))
  15. x <- utils::modifyList(y, x, TRUE)
  16. utils::modifyList(z, x, TRUE)
  17. }
  18. wrap_result <- function(x, escape = FALSE) {
  19. if (is.null(x$idx[[1]])) return(x$text)
  20. text <- x$text
  21. idx <- x$idx
  22. len_idx <- length(idx)
  23. inserts <- data.frame(
  24. i = 1:len_idx - 1,
  25. start = purrr::map_int(idx, ~ .[1]),
  26. end = purrr::map_int(idx, ~ .[2]) + 1
  27. ) %>%
  28. mutate(
  29. class = sprintf("group g%02d", i),
  30. pad = 0
  31. )
  32. for (j in seq_len(nrow(inserts))) {
  33. if (inserts$i[j] == 0) next
  34. overlap <- filter(
  35. inserts,
  36. i != 0,
  37. start <= !!inserts$start[j] & end > !!inserts$end[j])
  38. inserts[j, 'pad'] <- inserts$pad[j] + nrow(overlap)
  39. }
  40. inserts <- inserts %>%
  41. tidyr::gather(type, loc, start:end) %>%
  42. mutate(
  43. class = ifelse(pad > 0, sprintf("%s pad%02d", class, pad), class),
  44. insert = ifelse(type == 'start', sprintf('<span class="%s">', class), "</span>")
  45. ) %>%
  46. group_by(loc, type) %>%
  47. summarize(insert = paste(insert, collapse = ''))
  48. idx_split <- c(0 - (inserts$loc[1] == 0), inserts$loc)
  49. if (!(nchar(text) + 1) %in% idx_split) idx_split <- c(idx_split, nchar(text) + 1)
  50. text_split <- c()
  51. for (k in seq_along(idx_split[-1])) {
  52. text_split <- c(text_split, substr(text, idx_split[k], idx_split[k+1] - 1))
  53. }
  54. out <- c()
  55. for (j in seq_along(text_split)) {
  56. out <- c(
  57. out,
  58. ifelse(escape, escape_html(text_split[j]), text_split[j]),
  59. if (!is.na(inserts$insert[j])) inserts$insert[j]
  60. )
  61. }
  62. paste(out, collapse = '')
  63. }
  64. wrap_regex <- function(pattern, escape = TRUE, exact = TRUE) {
  65. stopifnot(length(pattern) == 1)
  66. if(escape) pattern <- escape_html(pattern)
  67. r_open_parens <- "(?<![\\\\])\\("
  68. x <- strsplit(pattern, r_open_parens, perl = TRUE)[[1]]
  69. first <- x[1]
  70. x <- x[-1]
  71. x <- paste0(
  72. '<span class="g', sprintf("%02d", seq_along(x)), '">(',
  73. x,
  74. collapse = ""
  75. )
  76. x <- gsub("(?<![\\\\])\\)", ")</span>", x, perl = TRUE)
  77. if (exact) x <- gsub("\\\\", "\\\\\\\\", x)
  78. paste0(first, x)
  79. }
  80. #' View grouped regex results
  81. #'
  82. #' @param text Text to search
  83. #' @param pattern Regex pattern to look for
  84. #' @param render Render results to an HTML doc and open in RStudio viewer?
  85. #' @param escape Escape HTML-related characters in `text`?
  86. #' @param knitr Print into knitr doc? If `TRUE`, marks text as `asis_output` and
  87. #' sets `render = FALSE` and `escape = TRUE`.
  88. #' @param exact Should regex be displayed as entered by the user into R console
  89. #' or source (default)? When `TRUE`, regex is displayed with the double `\\`
  90. #' required for escaping backslashes in R. When `FALSE`, regex is displayed
  91. #' as interpreted by the regex engine (i.e. double `\\` as a single `\`).
  92. #' @param ... Passed to [run_regex]
  93. #' @export
  94. view_regex <- function(
  95. text,
  96. pattern,
  97. ...,
  98. render = TRUE,
  99. escape = render,
  100. knitr = FALSE,
  101. exact = escape
  102. ) {
  103. if (knitr) {
  104. render <- FALSE
  105. escape <- TRUE
  106. }
  107. res <- run_regex(text, pattern, ...)
  108. res <- purrr::map_chr(res, wrap_result, escape = escape)
  109. res <- paste("<p class='results'>", res, "</p>")
  110. if (knitr) return(knitr::asis_output(res))
  111. if (!render) return(res)
  112. head <- c(
  113. "---", "pagetitle: View Regex", "---",
  114. "<h5>Regex</h5>",
  115. "<p><pre style = 'font-size: 1em;'>", wrap_regex(pattern, escape, exact), "</pre></p>",
  116. "<h5>Results</h5>"
  117. )
  118. res <- c(head, res)
  119. tmp <- tempfile(fileext = ".Rmd")
  120. cat(res, file = tmp, sep = "\n")
  121. tmp_html <- suppressWarnings(
  122. rmarkdown::render(
  123. tmp,
  124. output_format = rmarkdown::html_document(css = system.file('style.css', package='regexhelp')),
  125. quiet = TRUE
  126. ))
  127. rstudioapi::viewer(tmp_html)
  128. }