🔍 An RStudio addin slash regex utility belt
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

165 lines
5.3KB

  1. #' Extract matched groups from regexp
  2. #'
  3. #' @param text Text to search
  4. #' @param pattern regexp
  5. #' @inheritParams base::regexec
  6. #' @export
  7. run_regex <- function(
  8. text,
  9. pattern,
  10. ignore.case = FALSE,
  11. perl = FALSE,
  12. fixed = FALSE,
  13. useBytes = FALSE,
  14. invert = FALSE
  15. ) {
  16. # Use regex to get matches by group, gives start index and length
  17. m <- regexec(pattern, text, ignore.case, perl, fixed, useBytes)
  18. # Convert to start/end index
  19. x <- purrr::map(m, function(mi) {
  20. list(
  21. 'idx' = purrr::map2(mi, attr(mi, "match.length"),
  22. ~ if(.x[1] != -1) c(.x, .x + .y - 1L)))
  23. })
  24. # Store text and original regexc result with same hierarchy
  25. y <- purrr::map(text, ~ list(text = .))
  26. z <- purrr::map(regmatches(text, m), ~ list(m = .))
  27. # Zip text, indexes and regexc match object lists
  28. purrr::map(seq_along(x), ~ list(text = y[[.]][[1]], idx = x[[.]][[1]], m = z[[.]][[1]]))
  29. }
  30. wrap_result <- function(x, escape = FALSE) {
  31. if (is.null(x$idx[[1]])) return(if (escape) escape_html(x$text) else x$text)
  32. text <- x$text
  33. idx <- x$idx
  34. len_idx <- length(idx)
  35. inserts <- data.frame(
  36. i = 1:len_idx - 1,
  37. start = purrr::map_int(idx, ~ .[1]),
  38. end = purrr::map_int(idx, ~ .[2]) + 1
  39. ) %>%
  40. mutate(
  41. class = sprintf("group g%02d", .data$i),
  42. pad = 0
  43. )
  44. for (j in seq_len(nrow(inserts))) {
  45. if (inserts$i[j] == 0) next
  46. overlap <- filter(
  47. inserts[1:(j-1), ],
  48. .data$i != 0,
  49. .data$start <= !!inserts$start[j] & .data$end >= !!inserts$end[j])
  50. inserts[j, 'pad'] <- inserts$pad[j] + nrow(overlap)
  51. }
  52. inserts <- inserts %>%
  53. tidyr::gather(type, loc, start:end) %>%
  54. mutate(
  55. class = ifelse(.data$pad > 0, sprintf("%s pad%02d", .data$class, .data$pad), .data$class),
  56. insert = ifelse(.data$type == 'start', sprintf('<span class="%s">', .data$class), "</span>")
  57. ) %>%
  58. group_by(.data$loc, .data$type) %>%
  59. summarize(insert = paste(.data$insert, collapse = ''))
  60. # inserts now gives html (span open and close) to insert and loc
  61. # first split text at inserts$loc locations,
  62. # then recombine by zipping with inserts$insert text
  63. # start at 0, unless there's a hit on first character
  64. # end at nchar(text) + 1 because window is idx[k] to idx[k+1]-1
  65. idx_split <- c(0 - (inserts$loc[1] == 0), inserts$loc)
  66. if (!(nchar(text) + 1) %in% idx_split)
  67. idx_split <- c(idx_split, nchar(text) + 1)
  68. text_split <- c()
  69. for (k in seq_along(idx_split[-1])) {
  70. text_split <- c(text_split, substr(text, idx_split[k], idx_split[k+1] - 1))
  71. }
  72. out <- c()
  73. for (j in seq_along(text_split)) {
  74. out <- c(
  75. out,
  76. ifelse(escape, escape_html(text_split[j]), text_split[j]),
  77. if (!is.na(inserts$insert[j])) inserts$insert[j]
  78. )
  79. }
  80. paste(out, collapse = '')
  81. }
  82. wrap_regex <- function(pattern, escape = TRUE, exact = TRUE) {
  83. stopifnot(length(pattern) == 1)
  84. if(escape) pattern <- escape_html(pattern)
  85. r_open_parens <- "(?<![\\\\])\\("
  86. x <- strsplit(pattern, r_open_parens, perl = TRUE)[[1]]
  87. first <- x[1]
  88. x <- x[-1]
  89. if (length(x)) {
  90. x <- paste0(
  91. '<span class="g', sprintf("%02d", seq_along(x)), '">(',
  92. x,
  93. collapse = ""
  94. )
  95. x <- gsub("(?<![\\\\])\\)", ")</span>", x, perl = TRUE)
  96. }
  97. if (exact) x <- escape_backslash(x)
  98. paste0(first, x)
  99. }
  100. #' View grouped regex results
  101. #'
  102. #' @param text Text to search
  103. #' @param pattern Regex pattern to look for
  104. #' @param render Render results to an HTML doc and open in RStudio viewer?
  105. #' @param escape Escape HTML-related characters in `text`?
  106. #' @param knitr Print into knitr doc? If `TRUE`, marks text as `asis_output` and
  107. #' sets `render = FALSE` and `escape = TRUE`.
  108. #' @param exact Should regex be displayed as entered by the user into R console
  109. #' or source (default)? When `TRUE`, regex is displayed with the double `\\`
  110. #' required for escaping backslashes in R. When `FALSE`, regex is displayed
  111. #' as interpreted by the regex engine (i.e. double `\\` as a single `\`).
  112. #' @param ... Passed to [run_regex]
  113. #' @export
  114. view_regex <- function(
  115. text,
  116. pattern,
  117. ...,
  118. render = TRUE,
  119. escape = render,
  120. knitr = FALSE,
  121. exact = escape
  122. ) {
  123. if (knitr) {
  124. render <- FALSE
  125. escape <- TRUE
  126. }
  127. res <- run_regex(text, pattern, ...)
  128. res <- purrr::map_chr(res, wrap_result, escape = escape)
  129. res <- purrr::map_chr(res, function(resi) {
  130. result_pad <- ""
  131. if (grepl("pad\\d{2}", resi)) {
  132. max_pad <- max(stringr::str_extract_all(resi, "pad\\d{2}")[[1]])
  133. max_pad_level <- as.integer(stringr::str_extract(max_pad, "\\d{2}"))
  134. if (max_pad_level - 3 > 0) {
  135. result_pad <- sprintf("pad%02d", max_pad_level - 3)
  136. }
  137. }
  138. paste("<p class='results", result_pad, "'>", resi, "</p>")
  139. })
  140. res <- paste(res, collapse = "")
  141. if (!nchar(pattern)) res <- paste("<p class='results'>", text, "</p>")
  142. if (knitr) return(knitr::asis_output(res))
  143. if (!render) return(res)
  144. head <- c(
  145. "---", "pagetitle: View Regex", "---",
  146. "<h5>Regex</h5>",
  147. "<p><pre style = 'font-size: 1em;'>", wrap_regex(pattern, escape, exact), "</pre></p>",
  148. "<h5>Results</h5>"
  149. )
  150. res <- c(head, res)
  151. tmp <- tempfile(fileext = ".Rmd")
  152. cat(res, file = tmp, sep = "\n")
  153. tmp_html <- suppressWarnings(
  154. rmarkdown::render(
  155. tmp,
  156. output_format = rmarkdown::html_document(css = system.file('style.css', package='regexhelp')),
  157. quiet = TRUE
  158. ))
  159. rstudioapi::viewer(tmp_html)
  160. }