🔍 An RStudio addin slash regex utility belt
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

833 lines
34KB

  1. #' RegExplain gadget
  2. #'
  3. #' @import miniUI
  4. #' @import shiny
  5. #' @param text Text to explore in gadget (editable using interface)
  6. #' @param start_page Open gadget to this tab, one of `"Text"`, `"RegEx"`,
  7. #' `"Output"`, or `"Help"`
  8. #' @export
  9. regex_gadget <- function(text = NULL,
  10. start_page = if (is.null(text)) "Text" else "RegEx") {
  11. stopifnot(requireNamespace("miniUI"), requireNamespace("shiny"))
  12. update_available <- check_version()
  13. # ---- UI ----
  14. ui <- miniPage(
  15. shiny::includeCSS(system.file("styles", "style.css", package = "regexplain")),
  16. shiny::includeCSS(system.file("styles", "gadget.css", package = "regexplain")),
  17. gadgetTitleBar(
  18. "RegExplain",
  19. right = miniTitleBarButton("done", "Send RegEx To Console", TRUE)
  20. ),
  21. miniTabstripPanel(
  22. selected = match.arg(start_page, c("Text", "RegEx", "Output", "Help")),
  23. # --- UI - Tab - Text ----
  24. miniTabPanel(
  25. "Text", icon = icon('file-text-o'),
  26. miniContentPanel(
  27. fillCol(
  28. textAreaInputAlt('text',
  29. label = "Text to search or parse",
  30. value = paste(text, collapse = "\n"),
  31. resize = "both",
  32. width = "100%",
  33. height="90%",
  34. placeholder = "Paste, enter, or edit your sample text here.")
  35. )
  36. )
  37. ),
  38. # ---- UI - Tab - Regex ----
  39. miniTabPanel(
  40. "RegEx", icon = icon('terminal'),
  41. miniContentPanel(
  42. fillCol(
  43. flex = c(1, 3),
  44. fillCol(
  45. flex = c(1, 1),
  46. fillRow(
  47. flex = c(5, 1),
  48. textInputCode('pattern', 'RegEx', width = "100%",
  49. placeholder = "Standard RegEx, e.g. \\w+_\\d{2,4}\\s+"),
  50. tags$div(style = "margin-top: 23px; margin-left:6px;",
  51. actionButton("show_templates", "Templates", class = "btn-success"))
  52. ),
  53. checkboxGroupInput(
  54. 'regex_options',
  55. label = HTML(
  56. '<div style="font-size: 1.25rem;">',
  57. 'Option Groups: ',
  58. '<span style="color: #337ab7;">RegExplain</span>,',
  59. '<span style="color: #5cb85c;">All</span>, ',
  60. '<span style="color: #f0ad4e;">Base only</span>',
  61. '</div>'
  62. ),
  63. inline = TRUE,
  64. width = "90%",
  65. choiceValues = list(
  66. "text_break_lines",
  67. "ignore.case",
  68. "fixed",
  69. "perl",
  70. "useBytes"),
  71. choiceNames = list(
  72. HTML('<span style="color: #337ab7;">Break Lines</span>'),
  73. HTML('<span style="color: #5cb85c;">Ignore Case</span>'),
  74. HTML('<span style="color: #5cb85c;">Fixed/Literal</span>'),
  75. HTML('<span style="color: #f0ad4e;">Perl Style</span>'),
  76. HTML('<span style="color: #f0ad4e;">Use Bytes</span>')),
  77. selected = c('text_break_lines')
  78. )
  79. ),
  80. tags$div(
  81. class = "gadget-result",
  82. style = "overflow-y: scroll; height: 100%;",
  83. htmlOutput('result')
  84. )
  85. )
  86. )
  87. ),
  88. # ---- UI - Tab - Output ----
  89. miniTabPanel(
  90. "Output", icon = icon("table"),
  91. miniContentPanel(
  92. fillCol(
  93. flex = c(1, 3),
  94. inputPanel(
  95. tags$div(
  96. width = "100%;",
  97. selectInput('regexFn', label = 'Apply Function',
  98. choices = regexFn_choices),
  99. tags$span(class = "help-block",
  100. style = "font-size:1.25rem; margin-top:-10px; margin-bottom:0px; margin-left:4px;",
  101. "Adjust options in RegEx tab")
  102. ),
  103. uiOutput("output_sub")
  104. ),
  105. # verbatimTextOutput('output_result', placeholder = TRUE)
  106. tags$pre(
  107. id = "output_result",
  108. class = "shiny-text-output",
  109. style = "overflow-y: scroll; height: 100%;"
  110. )
  111. )
  112. )
  113. ),
  114. # ---- UI - Tab - Help ----
  115. miniTabPanel(
  116. "Help", icon = icon("support"),
  117. generate_help_ui(cheatsheet_only = FALSE)
  118. )
  119. )
  120. )
  121. # ---- Server ----
  122. server <- function(input, output, session) {
  123. if (!is.null(update_available)) {
  124. showModal(
  125. modalDialog(
  126. title = "Update Available \U1F389",
  127. easyClose = TRUE,
  128. footer = modalButton("OK"),
  129. tagList(
  130. tags$p(
  131. "Version", update_available$version, "is",
  132. tags$a(href = update_available$link,
  133. "available on GitHub.")
  134. ),
  135. if ("devtools" %in% installed.packages()) tags$p(
  136. "The fastest way to update is with devtools:",
  137. tags$pre(
  138. "devtools::update_packages(\"gadenbuie/regexplain\")"
  139. )
  140. ),
  141. tags$p(
  142. class = 'help-block',
  143. "This message won't be shown again during this R session."
  144. )
  145. )
  146. )
  147. )
  148. }
  149. # ---- Server - Global ----
  150. rtext <- reactive({
  151. x <- if ('text_break_lines' %in% input$regex_options) {
  152. strsplit(input$text, "\n")[[1]]
  153. } else input$text
  154. x
  155. })
  156. pattern <- reactive({
  157. sanitize_text_input(input$pattern)
  158. })
  159. alert_result <- function(msg, type = "danger") {
  160. msg <- gsub("\n", "<br>", msg)
  161. msg <- gsub("\t", "&nbsp;&nbsp;", msg)
  162. paste0("<pre class='alert alert-", type, "' ",
  163. "style='padding: 4px; margin-top: 1px; margin-bottom: 4px;'>",
  164. paste(msg, collapse = "<br>"),
  165. "</pre>")
  166. }
  167. # ---- Server - Tab - Regex ----
  168. output$result <- renderUI({
  169. if (is.null(rtext())) return(NULL)
  170. if (pattern() == "") {
  171. return(toHTML(paste('<p class="results">', escape_html(rtext()), "</p>", collapse = "")))
  172. }
  173. res <- NULL
  174. error_message <- NULL
  175. warning_message <- NULL
  176. tryCatch({
  177. res <- paste(
  178. view_regex(
  179. rtext(),
  180. pattern(),
  181. ignore.case = 'ignore.case' %in% input$regex_options,
  182. perl = 'perl' %in% input$regex_options,
  183. fixed = 'fixed' %in% input$regex_options,
  184. useBytes = 'useBytes' %in% input$regex_options,
  185. # invert = 'invert' %in% input$regex_options,
  186. render = FALSE,
  187. escape = TRUE,
  188. exact = FALSE),
  189. collapse = ""
  190. )
  191. },
  192. error = function(e) {
  193. error_message <<- alert_result(e$message, "danger")
  194. },
  195. warning = function(w) {
  196. warning_message <<- alert_result(w$message, "warning")
  197. })
  198. if (is.null(res)) res <- toHTML(
  199. paste('<p class="results">', escape_html(rtext()), "</p>", collapse = "")
  200. )
  201. toHTML(paste(error_message, warning_message, res))
  202. })
  203. # ---- Server - Tab - RegEx - Templates ----
  204. templates <- get_templates()
  205. this_template <- reactive({
  206. req(input$template)
  207. purrr::keep(templates, ~ .$name == input$template) %>%
  208. purrr::flatten()
  209. })
  210. observeEvent(input$show_templates, {
  211. showModal(
  212. modalDialog(
  213. title = "Templates",
  214. footer = tagList(
  215. modalButton("Cancel"),
  216. actionButton("apply_template", "Use Template", class = "btn-success")
  217. ),
  218. selectInput("template", "Template",
  219. choices = c("Choose template" = "",
  220. purrr::set_names(purrr::map_chr(templates, 'name')))),
  221. uiOutput("template_info")
  222. )
  223. )
  224. })
  225. output$template_info <- renderUI({
  226. req(this_template())
  227. tagList(
  228. tags$h5("Description"),
  229. tags$p(this_template()$description),
  230. tags$h5("Pattern"),
  231. tags$pre(
  232. tags$code(
  233. this_template()$regex
  234. )
  235. )
  236. )
  237. })
  238. observeEvent(input$apply_template, {
  239. updateTextInput(session, "pattern", value = this_template()$regex)
  240. updateSelectInput(session, "template", selected = "")
  241. removeModal()
  242. })
  243. # ---- Server - Tab - Output ----
  244. regexFn_replacement_val <- NULL
  245. output$output_sub <- renderUI({
  246. req(input$regexFn)
  247. if (!input$regexFn %in% regexFn_substitute) return(NULL)
  248. textInputCode('regexFn_replacement', 'Subsitution',
  249. value = regexFn_replacement_val,
  250. placeholder = "Replacement Text")
  251. })
  252. replacement <- reactive({
  253. req(input$regexFn)
  254. if (!input$regexFn %in% regexFn_substitute) {
  255. NULL
  256. } else {
  257. regexFn_replacement_val <<- input$regexFn_replacement
  258. sanitize_text_input(input$regexFn_replacement)
  259. }
  260. })
  261. output$output_result <- renderPrint({
  262. req(input$regexFn)
  263. regexPkg <- get_pkg_namespace(input$regexFn)
  264. if (!requireNamespace(regexPkg, quietly = TRUE)) {
  265. return(cat(
  266. paste0(
  267. "The package `", regexPkg, "` is not installed.\n",
  268. "To preview results from this package, please run\n\n",
  269. " install.packages(\"", regexPkg, "\")"
  270. )
  271. ))
  272. }
  273. regexFn <- getFromNamespace(input$regexFn, regexPkg)
  274. req_sub_arg <- input$regexFn %in% regexFn_substitute
  275. x <- if (regexPkg == "base") {
  276. if (req_sub_arg) {
  277. req(replacement())
  278. regexFn(pattern(), replacement(), rtext(),
  279. ignore.case = 'ignore.case' %in% input$regex_options,
  280. perl = 'perl' %in% input$regex_options,
  281. fixed = 'fixed' %in% input$regex_options,
  282. useBytes = 'useBytes' %in% input$regex_options)
  283. } else {
  284. regexFn(pattern(), rtext(),
  285. ignore.case = 'ignore.case' %in% input$regex_options,
  286. perl = 'perl' %in% input$regex_options,
  287. fixed = 'fixed' %in% input$regex_options,
  288. useBytes = 'useBytes' %in% input$regex_options)
  289. }
  290. } else if (regexPkg == "stringr") {
  291. if (req_sub_arg) {
  292. req(replacement())
  293. regexFn(
  294. rtext(),
  295. stringr::regex(
  296. pattern(),
  297. ignore_case = 'ignore.case' %in% input$regex_options,
  298. literal = 'fixed' %in% input$regex_options
  299. ),
  300. replacement()
  301. )
  302. } else {
  303. regexFn(
  304. rtext(),
  305. stringr::regex(
  306. pattern(),
  307. ignore_case = 'ignore.case' %in% input$regex_options,
  308. literal = 'fixed' %in% input$regex_options
  309. )
  310. )
  311. }
  312. } else if (regexPkg == "rematch2") {
  313. regexFn(rtext(), pattern(),
  314. ignore.case = 'ignore.case' %in% input$regex_options,
  315. perl = 'perl' %in% input$regex_options,
  316. fixed = 'fixed' %in% input$regex_options,
  317. useBytes = 'useBytes' %in% input$regex_options)
  318. } else {
  319. "Um. Not sure how I got here."
  320. }
  321. print(x)
  322. })
  323. # ---- Server - Tab - Help ----
  324. HELP_DEFAULT_TEXT <- c(
  325. "<h3>Welcome to RegExplain</h3>",
  326. "<p>If you’re new to regular expressions, one of the best places to start is <a href=\"http://stringr.tidyverse.org/articles/regular-expressions.html\">the regular expressions vignette</a> from <code>stringr</code>. The chapter on strings in <a href=\"http://r4ds.had.co.nz/strings.html\">R for Data Science</a> is also an excellent first resource.</p>",
  327. "<p><strong>Exploring or looking for a challenge?</strong> Click on <i>Try These Examples</i> to see what you can do with this addin.</p>",
  328. "<h4>Getting Started</h4>",
  329. "<ul>",
  330. "<li><p><i class=\"fa fa-file-text-o\"></i> Enter or edit the <strong>Text</strong> you want to search.</p></li>",
  331. "<li><p><i class=\"fa fa-terminal\"></i> Edit your <strong>RegEx</strong> and view matches in real time.</p></li>",
  332. "<li><p><i class=\"fa fa-table\"></i> Test the <strong>Output</strong> of your regular expression with common functions, including <i>search and replace</i> functions.</p></li>",
  333. "<li><p><i class=\"fa fa-support\"></i> Get <strong>Help</strong> and look up the regular expression syntax.</p></li>",
  334. "</ul>",
  335. "<h4>Escaping characters</h4>",
  336. "<p>In order to store a backslash (<code>\\</code>) as a character in R, backslashes need to be escaped…with another backslash! To write a literal <code>\\</code> in an R character string, you need to actually store <code>&quot;\\\\&quot;</code>.</p>",
  337. "<p>In regular expressions, <code>\\w</code> stands for any alphabetical character, but to store it in a string in R you need <code>&quot;\\w&quot;</code>.</p>",
  338. "<p>Inside <strong>RegExplain</strong>, however, standard regular expressions can be used so that you can easily copy patterns from other places. When you click on the <span class=\"btn btn-xs btn-primary\">Send RegEX to Console</span> button, the necessary extra <code>\\</code> will be included.</p>",
  339. "<p>An extra backslash is still needed to match a literal <code>\\</code> in standard regular expressions. This means that you will need to enter <code>\\\\</code> in the <strong>RegEx</strong> tab, and the output to R will be <code>&quot;\\\\\\\\&quot;</code>.</p>"
  340. )
  341. source(system.file("shiny", "help_server.R", package = "regexplain"), local = TRUE)
  342. observeEvent(input$help_resources, {
  343. tagList(
  344. tags$h3("Resources"),
  345. tags$p("There are lots of great resources available for learning and working with regular expressions."),
  346. tags$h4("Regular Expressions in R"),
  347. tags$ul(
  348. tags$li(tags$p("The", tags$a(href = "http://stringr.tidyverse.org/articles/regular-expressions.html", "Regular Expressions vignette"),
  349. "from", tags$code("stringr"), "is an excellent first introduction to regular expressions in R.")),
  350. tags$li(tags$p("The", tags$a(href = "http://r4ds.had.co.nz/strings.html", "chapter on strings"),
  351. "in", tags$a(href = "http://r4ds.had.co.nz/", "R for Data Science"),
  352. "is also a great overall introduction.")),
  353. tags$li(tags$p("RStudio's",
  354. tags$a(href = "https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf", "RegEx CheatSheet"),
  355. "is a good pocket reference.")),
  356. tags$li(tags$p("Or try the", tags$strong("Regexplain Cheatsheet"), "addin installed with this package."))
  357. ),
  358. tags$h4("Online Resources"),
  359. tags$ul(
  360. tags$li(tags$a(href = "https://github.com/aloisdg/awesome-regex", "Awesome RegEx")),
  361. tags$li(tags$a(href = "https://www.regular-expressions.info", "Regular-Expressions.info")),
  362. tags$li(tags$a(href = "https://projects.lukehaas.me/regexhub", "Regex Hub"), "- common regex patterns"),
  363. tags$li(tags$a(href = "http://regexlib.com/DisplayPatterns.aspx", "RegExLib.com"), "- large collection of searchable patterns")
  364. ),
  365. tags$h4("Live Preview and Explanations"),
  366. tags$ul(
  367. tags$li(tags$a(href = "https://regexr.com", "https://regexr.com")),
  368. tags$li(tags$a(href = "https://regexper.com/", "https://regexper.com")),
  369. tags$li(tags$a(href = "https://debuggex.com", "https://debuggex.com")),
  370. tags$li(tags$a(href = "https://regex101.com", "https://regex101.com")),
  371. tags$li(tags$a(href = "http://rick.measham.id.au/paste/explain", "http://rick.measham.id.au/paste/explain")),
  372. tags$li(tags$a(href = "http://www.mactechnologies.com/index.php?page=downloads#regexrx", "RegexRx"), "(app)"),
  373. tags$li(tags$a(href = "https://www.regexbuddy.com/", "Regex Buddy"), "(paid app)")
  374. ),
  375. tags$h4("Regex and String R Packages"),
  376. tags$dl(
  377. tags$dt(tags$a(href = "https://stringr.tidyverse.org/", "stringr")),
  378. tags$dd("A cohesive set of functions designed to make working with strings as easy as possible"),
  379. tags$dt(tags$a(href = "http://www.gagolewski.com/software/stringi/", "stringi")),
  380. tags$dd("THE R package for very fast, correct, consistent, and convenient string/text processing"),
  381. tags$dt(tags$a(href = "https://github.com/trinker/regexr", "regexr")),
  382. tags$dd("An R framework for constructing and managing human readable regular expressions"),
  383. tags$dt(tags$a(href = "https://github.com/kevinushey/rex", "rex")),
  384. tags$dd("Friendly Regular Expressions: complex regular expressions from human readable expressions"),
  385. tags$dt(tags$a(href = "https://github.com/richierocks/rebus", "rebus")),
  386. tags$dd("Build regular expressions in a human readable way"),
  387. tags$dt(tags$a(href = "https://www.r-pkg.org/pkg/qdapRegex", "qdapRegex")),
  388. tags$dd("A collection of regular expression tools for extraction/removal/replacement of common patterns in text documents"),
  389. tags$dt(tags$a(href = "https://github.com/AdamSpannbauer/r_regex_tester_app", "R Regex Tester")),
  390. tags$dd("A Shiny app for testing regular expressions")
  391. )
  392. ) %>%
  393. as.character() %>%
  394. help_text()
  395. })
  396. load_buttons <- function(..., extra_btns = NULL) {
  397. prefix <- paste(..., sep = "_")
  398. btns <- c(
  399. list(c("text", "Load Text", "btn-success"),
  400. c("pattern", "Load Pattern", "btn-primary")),
  401. extra_btns
  402. )
  403. tags$span(
  404. style = "display: inline-block;",
  405. purrr::map(
  406. btns,
  407. ~ actionButton(paste0(prefix, "_", .[1]), .[2], class = paste("btn-xs", if (!is.na(.[3])) .[3]))
  408. )
  409. )
  410. }
  411. observeEvent(input$help_try_this, {
  412. tagList(
  413. tags$h3("Try These Examples"),
  414. tags$p("Here are a couple interesting text extraction challenges you can try",
  415. "with this gadget."),
  416. tags$h4("Harvard Sentences"),
  417. tags$p("These examples come from the",
  418. tags$a(href = "http://r4ds.had.co.nz/strings.html", "R for Data Science"),
  419. "book and are based on a collection of short sentences called the Harvard Sentences."),
  420. tags$ol(
  421. tags$li(tags$p(
  422. "Find sentences that contain a color (i.e. red, orange, yellow, green, blue, purple).",
  423. load_buttons("help_try_this", "hs", "colors"))),
  424. tags$li(tags$p(
  425. "Use the text from Exercise 1 and make sure that only full words that are colors are found.",
  426. HTML("E.g. <code>red</code> and not <code>flickered</code>."),
  427. tags$span(style = "display: inline-block;",
  428. actionButton("help_try_this_hs_colors_word", "Load Pattern", class = "btn-xs btn-primary"),
  429. actionButton("help_try_this_hs_colors_hint", "Show Hint", class = "btn-xs"))
  430. )),
  431. tags$li(tags$p(
  432. "Extract nouns from sentences by finding any word that comes after \"a\" or \"the\".",
  433. "Use", actionLink("help_try_this_hs_words_go2_groups", "Groups"),
  434. "to extract the article and possible noun separately and check your results with",
  435. HTML("<code>stringr::str_match()</code>:"),
  436. load_buttons("help_try_this", "hs", "words",
  437. extra_btns = list(c("output", "Check str_match()")))
  438. )),
  439. tags$li(tags$p(
  440. "Switch the order of the two words following the articles", '"a" or "the"',
  441. "using", actionLink("help_try_this_hs_refs_go2_groups", "backreferences,"),
  442. "so that", tags$code("the birch canoe"), "would read",
  443. HTML("<code>the canoe birch</code>. Use <code>sub</code>"),
  444. "in the", tags$strong("Output"), "tab to replace the matched pattern.",
  445. load_buttons("help_try_this", "hs", "refs",
  446. extra_btns = list(c("output", "Load Replacement")))
  447. ))
  448. ),
  449. tags$h4("Phone Numbers"),
  450. tags$p("This example is also from the",
  451. tags$a(href = "http://r4ds.had.co.nz/strings.html#other-types-of-pattern",
  452. "R for Data Science"),
  453. "book. Phone numbers in the United States start with a 3-digit area code,",
  454. "followed by another 3 digits and a final 4-digit group.",
  455. "Sometimes the area code is wrapped in parenthesis, or sometimes dots or dashes",
  456. "are used to separate the digit groups. Try to extract each digit group from these phone numbers:",
  457. load_buttons("help_try_this", "phone",
  458. extra_btns = list(c("output", "Check str_match()")))),
  459. tags$h4("CSS Unit Validation"),
  460. tags$p("This example is used in", tags$code("validateCssUnit()"),
  461. "in the", tags$a(href="https://www.r-pkg.org/pkg/htmltools", "htmltools package."),
  462. "CSS units can be integer or decimal numbers with units such as",
  463. "in, cm, mm, em, ex, pt, px, etc. (see the list",
  464. HTML('<a href="https://www.w3.org/Style/Examples/007/units.en.html">here</a>).'),
  465. "Try to extract the number and unit from these units:",
  466. load_buttons("help_try_this", "css")),
  467. tags$h4("Parse Github Repos"),
  468. tags$p("This example is from the",
  469. tags$a(href = "https://www.r-pkg.org/pkg/rematch2", "rematch2 package."),
  470. "Github repositories are often specified in like",
  471. HTML("<code>user/repo/subdir@ref*release</code> or <code>user/repo/subdir#PR</code>"),
  472. "where only", tags$code("user"), "and", tags$code("repo"), "are required elements.",
  473. "Try to extract each piece of the repo text and use",
  474. tags$code("rematch2::re_match()"), "to extract a tidy tibble of matches:",
  475. load_buttons("help_try_this", "github",
  476. extra_btns = list(c("output", "Check re_match()"))))
  477. ) %>%
  478. as.character() %>%
  479. help_text()
  480. })
  481. observeEvent(input$help_try_this_hs_colors_text, {
  482. color_match <- "\\b(red|orange|yellow|green|blue|purple)\\b|red"
  483. color_text <- stringr::sentences[grepl(color_match, stringr::sentences)]
  484. color_text <- sample(color_text, 25)
  485. updateTextAreaInput(session, "text", value = paste(color_text, collapse = "\n"))
  486. showNotification("Text loaded! View it in Text tab", type = 'message')
  487. })
  488. observeEvent(input$help_try_this_hs_colors_pattern, {
  489. color_match <- "red|orange|yellow|green|blue|purple"
  490. updateTextInput(session, 'pattern', value = color_match)
  491. updateCheckboxGroupInput(session, "regex_options", selected = c('text_break_lines', 'perl'))
  492. showNotification("Pattern loaded! View it in RegEx tab", type = 'message')
  493. })
  494. observeEvent(input$help_try_this_hs_colors_word, {
  495. color_match <- "\\b(red|orange|yellow|green|blue|purple)\\b"
  496. updateTextInput(session, 'pattern', value = color_match)
  497. updateCheckboxGroupInput(session, "regex_options", selected = c('text_break_lines', 'perl'))
  498. showNotification("Pattern loaded! View it in RegEx tab", type = 'message')
  499. })
  500. observeEvent(input$help_try_this_hs_colors_hint, {
  501. showModal(
  502. modalDialog(title = "Hint \U0001f575", footer = NULL, easyClose = TRUE,
  503. tags$p("Try using the", tags$strong("word boundary"), "anchor."))
  504. )
  505. })
  506. observeEvent(input$help_try_this_hs_words_go2_groups, {
  507. make_help_tab_text("groups")
  508. })
  509. observeEvent(input$help_try_this_hs_words_output, {
  510. updateSelectInput(session, 'regexFn', selected = 'str_match')
  511. showNotification("Go to Output tab to see results from str_match()", type = "message")
  512. })
  513. observeEvent(input$help_try_this_hs_words_text, {
  514. hs_text <- sample(stringr::sentences, 25)
  515. updateTextAreaInput(session, "text", value = paste(hs_text, collapse = "\n"))
  516. showNotification("Text loaded! View it in Text tab", type = 'message')
  517. })
  518. observeEvent(input$help_try_this_hs_words_pattern, {
  519. noun_pattern <- "(a|the) ([^ ]+)"
  520. updateTextInput(session, 'pattern', value = noun_pattern)
  521. updateCheckboxGroupInput(session, "regex_options", selected = c('text_break_lines'))
  522. updateSelectInput(session, 'regexFn', selected = "str_match")
  523. showNotification("Pattern loaded! View it in RegEx and Output tabs", type = 'message')
  524. })
  525. observeEvent(input$help_try_this_hs_refs_go2_groups, {
  526. make_help_tab_text("groups")
  527. })
  528. observeEvent(input$help_try_this_hs_refs_output, {
  529. regexFn_replacement_val <<- "\\1 \\3 \\2"
  530. updateSelectInput(session, 'regexFn', selected = 'sub')
  531. showNotification("Replacement loaded! Go to Output tab to see results", type = "message")
  532. })
  533. observeEvent(input$help_try_this_hs_refs_text, {
  534. hs_text <- sample(stringr::sentences, 25)
  535. updateTextAreaInput(session, "text", value = paste(hs_text, collapse = "\n"))
  536. showNotification("Text loaded! View it in Text tab", type = 'message')
  537. })
  538. observeEvent(input$help_try_this_hs_refs_pattern, {
  539. noun_pattern <- "(a|the) ([^ ]+) ([^ ]+)"
  540. updateTextInput(session, 'pattern', value = noun_pattern)
  541. updateCheckboxGroupInput(session, "regex_options", selected = c('text_break_lines'))
  542. showNotification("Pattern loaded! View it in RegEx tab", type = 'message')
  543. })
  544. observeEvent(input$help_try_this_phone_output, {
  545. updateSelectInput(session, 'regexFn', selected = 'str_match')
  546. showNotification("Go to Output tab to see results from str_match()", type = "message")
  547. })
  548. observeEvent(input$help_try_this_phone_text, {
  549. phone_number <- function() {
  550. first <- function() sample(2:9, 1)
  551. others <- function(n) sample(1:9, n, replace = TRUE)
  552. wrap_types <- c("parens", "dash", "space", "dot", "nothing")
  553. wrap <- function(x, type) {
  554. switch(
  555. match.arg(type, choices = wrap_types),
  556. parens = paste0("(", x, ")"),
  557. dash = paste0(x, "-"),
  558. space = paste0(x, " "),
  559. dot = paste0(x, "."),
  560. x
  561. )
  562. }
  563. area_code <- paste0(c(first(), others(2)), collapse = "")
  564. group1 <- paste0(c(first(), others(2)), collapse = "")
  565. group2 <- paste0(c(first(), others(3)), collapse = "")
  566. area_wrap <- sample(wrap_types, 1)
  567. other_wrap <- if (area_wrap == "parens") sample(wrap_types[-1], 1) else area_wrap
  568. paste0(wrap(area_code, area_wrap), wrap(group1, other_wrap), group2)
  569. }
  570. phone_numbers <- replicate(25, phone_number())
  571. updateTextAreaInput(session, "text", value = paste(phone_numbers, collapse = "\n"))
  572. showNotification("Text loaded! View it in Text tab", type = 'message')
  573. })
  574. observeEvent(input$help_try_this_phone_pattern, {
  575. phone_pattern <- "\\(?(\\d{3})[-). ]?(\\d{3})[- .]?(\\d{4})"
  576. updateTextInput(session, 'pattern', value = phone_pattern)
  577. updateCheckboxGroupInput(session, "regex_options", selected = c('text_break_lines'))
  578. showNotification("Pattern loaded! View it in RegEx tab", type = 'message')
  579. })
  580. observeEvent(input$help_try_this_github_text, {
  581. github_repos <- c(
  582. "metacran/crandb",
  583. "jeroenooms/curl@v0.9.3",
  584. "jimhester/covr#47",
  585. "hadley/dplyr@*release",
  586. "r-lib/remotes@550a3c7d3f9e1493a2ba"
  587. )
  588. updateTextAreaInput(session, "text", value = paste(github_repos, collapse = "\n"))
  589. showNotification("Text loaded! Go to RegEx Tab", type = 'message')
  590. })
  591. observeEvent(input$help_try_this_github_pattern, {
  592. owner_rx <- "(?:(?<owner>[^/]+)/)?"
  593. repo_rx <- "(?<repo>[^/@#]+)"
  594. subdir_rx <- "(?:/(?<subdir>[^@#]*[^@#/]))?"
  595. ref_rx <- "(?:@(?<ref>[^*].*))"
  596. pull_rx <- "(?:#(?<pull>[0-9]+))"
  597. release_rx <- "(?:@(?<release>[*]release))"
  598. subtype_rx <- sprintf("(?:%s|%s|%s)?", ref_rx, pull_rx, release_rx)
  599. github_rx <- sprintf(
  600. "^(?:%s%s%s%s|(?<catchall>.*))$",
  601. owner_rx, repo_rx, subdir_rx, subtype_rx
  602. )
  603. updateTextInput(session, 'pattern', value = github_rx)
  604. updateCheckboxGroupInput(session, "regex_options", selected = c('text_break_lines', 'perl'))
  605. showNotification("Pattern loaded! Go to RegEx Tab", type = 'message')
  606. })
  607. observeEvent(input$help_try_this_github_output, {
  608. updateSelectInput(session, 'regexFn', selected = 're_match')
  609. showNotification("Go to Output tab to see results from re_match()", type = "message")
  610. })
  611. observeEvent(input$help_try_this_css_text, {
  612. css_units <- c(
  613. "125%","16pt","2cm","7em","3ex","24pt",
  614. ".15in","20pc","5.9vw","3.0vh","2vmin"
  615. )
  616. showNotification("Example text loaded! Go to RegEx tab", type = "message")
  617. updateTextAreaInput(session, "text", value = paste(css_units, collapse = "\n"))
  618. })
  619. observeEvent(input$help_try_this_css_pattern, {
  620. pattern <- "^(auto|inherit|((\\.\\d+)|(\\d+(\\.\\d+)?))(%|in|cm|mm|em|ex|pt|pc|px|vh|vw|vmin|vmax))$"
  621. updateTextInput(session, "pattern", value = pattern)
  622. updateCheckboxGroupInput(session, 'regex_options', selected = c('text_break_lines', 'perl'))
  623. showNotification("Pattern loaded! Go to RegEx tab", type = "message")
  624. })
  625. # ---- Server - Tab - Exit ----
  626. observeEvent(input$done, {
  627. if (pattern() != "") {
  628. pattern <- paste0('pattern <- "', escape_backslash(pattern()), '"')
  629. if ("regexFn_replacement" %in% names(input) && replacement() != "") {
  630. pattern <- paste0(
  631. pattern, "\n",
  632. 'replacement <- "', escape_backslash(replacement()), '"'
  633. )
  634. }
  635. rstudioapi::sendToConsole(pattern, FALSE)
  636. }
  637. stopApp()
  638. })
  639. observeEvent(input$cancel, {
  640. stopApp()
  641. })
  642. }
  643. viewer <- shiny::paneViewer(minHeight = 1000)
  644. runGadget(ui, server, viewer = viewer)
  645. }
  646. # ---- Gadget Helper Functions and Variables ----
  647. sanitize_text_input <- function(x) {
  648. if (is.null(x) || !nchar(x)) return(x)
  649. rx_unicode <- "\\\\u[0-9a-f]{4,8}"
  650. rx_hex <- "\\\\x[0-9a-f]{2}|\\\\x\\{[0-9a-f]{1,6}\\}"
  651. rx_octal <- "\\\\[0][0-7]{1,3}"
  652. rx_escape <- paste(rx_unicode, rx_hex, rx_octal, sep = "|")
  653. if (grepl(rx_escape, x, ignore.case = TRUE)) {
  654. try({
  655. y <- stringi::stri_unescape_unicode(x)
  656. }, silent = TRUE)
  657. if (!is.na(y)) x <- y
  658. }
  659. # x <- gsub("\u201C|\u201D", '"', x)
  660. # x <- gsub("\u2018|\u2019", "'", x)
  661. x
  662. }
  663. toHTML <- function(...) {
  664. x <- paste(..., collapse = "")
  665. x <- gsub("\n", "\\\\n", x)
  666. x <- gsub("\t", "\\\\t", x)
  667. x <- gsub("\r", "\\\\r", x)
  668. HTML(x)
  669. }
  670. regexFn_choices <- list(
  671. "Choose a function" = "",
  672. base = c(
  673. "grep",
  674. "grepl",
  675. "sub", #<<
  676. "gsub", #<<
  677. "regexpr",
  678. "gregexpr",
  679. "regexec"
  680. ),
  681. stringr = c(
  682. "str_detect",
  683. "str_locate",
  684. "str_locate_all",
  685. "str_extract",
  686. "str_extract_all",
  687. "str_match",
  688. "str_match_all",
  689. "str_replace", #<<
  690. "str_replace_all", #<<
  691. "str_split"
  692. ),
  693. "rematch2" = c(
  694. "re_match",
  695. "re_match_all",
  696. "re_exec",
  697. "re_exec_all"
  698. )
  699. )
  700. regexFn_substitute <- c(
  701. paste0(c("", "g"), "sub"),
  702. paste0("str_replace", c("", "_all"))
  703. )
  704. get_pkg_namespace <- function(fn) {
  705. x <- names(purrr::keep(regexFn_choices, ~ (fn %in% .)))
  706. if (length(x) > 1) warning(fn, " matches multiple functions in regexFn_choices, please review.")
  707. x
  708. }
  709. #' Check if an updated version is available
  710. #'
  711. #' I included this because it can be difficult to tell if your RStudio Addins
  712. #' are up to date. I may add new features that you want but you won't hear about
  713. #' the updates. This function checks if an update is available, using GitHub
  714. #' tags. If an update is available, a modal dialog is shown when you start
  715. #' the regexplain gadget. This only happens once per R session, though, so feel
  716. #' free to ignore the message.
  717. #'
  718. #' @param gh_user GitHub user account
  719. #' @param gh_repo GitHub repo name
  720. #' @param this_version The currently installed version of the package
  721. #' @keywords internal
  722. check_version <- function(
  723. gh_user = "gadenbuie",
  724. gh_repo = "regexplain",
  725. this_version = packageVersion('regexplain')
  726. ) {
  727. ok_to_check <- getOption("regexplain.no.check.version", TRUE)
  728. if (!ok_to_check) return(NULL)
  729. if (!requireNamespace('jsonlite', quietly = TRUE)) return(NULL)
  730. get_json <- purrr::possibly(jsonlite::fromJSON, NULL)
  731. gh_tags <- get_json(
  732. paste0("https://api.github.com/repos/", gh_user, "/", gh_repo, "/git/refs/tags"),
  733. simplifyDataFrame = TRUE
  734. )
  735. if (!is.null(gh_tags)) {
  736. gh_tags$tag <- sub("refs/tags/", "", gh_tags$ref, fixed = TRUE)
  737. gh_tags$version <- sub("^v\\.?", "", gh_tags$tag)
  738. }
  739. if (!is.null(gh_tags) && any(gh_tags$version > this_version)) {
  740. max_version <- max(gh_tags$version)
  741. max_tag <- gh_tags$tag[gh_tags$version == max_version]
  742. options(regexplain.no.check.version = FALSE)
  743. return(
  744. list(
  745. version = max_version,
  746. link = paste("https://github.com", gh_user, gh_repo, "releases/tag", max_tag, sep = "/")
  747. )
  748. )
  749. } else return(NULL)
  750. }
  751. #' Loads Regex Pattern Templates
  752. #'
  753. #' Sourced from [Regex Hub](https://projects.lukehaas.me/regexhub)
  754. #' and available at <https://github.com/lukehaas/RegexHub>. Copyright
  755. #' Luke Haas licensed under the MIT license available at
  756. #' <https://github.com/lukehaas/RegexHub/commit/3ab87b5a4fd2817b42e2e45dcf040d4f0164ea37>.
  757. #'
  758. #' @keywords internal
  759. get_templates <- function() {
  760. if (!requireNamespace("jsonlite")) {
  761. warning("Please install the `jsonlite` package to use template features")
  762. return(NULL)
  763. }
  764. f_patterns <- system.file("extdata", "patterns.json", package = "regexplain")
  765. if (!file.exists(f_patterns)) return(NULL)
  766. patterns <- jsonlite::fromJSON(
  767. f_patterns,
  768. simplifyVector = FALSE,
  769. simplifyDataFrame = FALSE,
  770. simplifyMatrix = FALSE
  771. )
  772. patterns[order(purrr::map_chr(patterns, 'name'))]
  773. }