Skip to content

Instantly share code, notes, and snippets.

@yutannihilation
Created January 27, 2019 03:00
Show Gist options
  • Save yutannihilation/2cc0b69ae953284bf02a4bd9daebf0ab to your computer and use it in GitHub Desktop.
Save yutannihilation/2cc0b69ae953284bf02a4bd9daebf0ab to your computer and use it in GitHub Desktop.
poor man's named capture group

See gagolews/stringi#153

Basic idea

Do this for all named capture group

stringi::stri_replace_all_regex("foo_bar", "(?<name>.*)_(?<value>.*)", "${value}")
#> [1] "bar"

Implementation

str_extract_named_capture_groups <- function(x, pattern) {
  groups <- stringi::stri_extract_all_regex(pattern, "(?<=\\(\\?<).*?(?=>)")[[1]]
  replacements <- paste0("${", groups, "}")
  names(replacements) <- groups
  
  purrr::map_dfc(replacements, ~ stringi::stri_replace_first_regex(x, pattern, .))
}

str_extract_named_capture_groups(c("foo_bar", "a_b"), "(?<name>.*)_(?<value>.*)")
#> # A tibble: 2 x 2
#>   name  value
#>   <chr> <chr>
#> 1 foo   bar  
#> 2 a     b

Created on 2019-01-27 by the reprex package (v0.2.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment