str_replace_verbose: Replace matched patterns in strings _verbosely_

str_replace_verboseR Documentation

Replace matched patterns in strings verbosely


Applies a series of regular-expression-replacement pairs to one or more strings. All performed replacements are displayed on the console by default (verbose = TRUE).


str_replace_verbose(string, pattern, verbose = TRUE, n_context_chrs = 20L)



Input vector. Either a character vector, or something coercible to one.


A named character vector with patterns as names and replacements as values (c(pattern1 = replacement1)). Patterns are interpreted as regular expressions as described in stringi::stringi-search-regex(). Replacements are interpreted as-is, except that references of the form ⁠\1⁠, ⁠\2⁠, etc. will be replaced with the contents of the respective matched group (created in patterns using ⁠()⁠). Pattern-replacement pairs are processed in the order given, meaning that first listed pairs are applied before later listed ones.


Whether or not to display replacements on the console.


The (maximum) number of characters displayed around the actual string and its replacement. The number refers to a single side of string/replacement, so the total number of context characters is at the maximum 2 * n_context_chrs. Only relevant if verbose = TRUE.


This function provides a subset of stringr::str_replace_all()'s functionality. If you don't need the visual console output, it's recommended to directly resort to the latter.


A character vector.

See Also

Other string functions: str_normalize(), str_normalize_file(), str_replace_file()


"Make love, not war" |>
  yay::str_replace_verbose(pattern = c("love" = "hummus",
                                       "war" = "walls"))

# pattern-replacement pairs are processed one-by-one, so the following gives the same result
"Make love, not war" |>
  yay::str_replace_verbose(pattern = c("love" = "hummus",
                                       "hummus, not war" = "hummus, not walls"))

# varying `n_context_chrs` affects console output summarization
input <- c("Tulips are not durable, ",
           "not scarce, ",
           "not programmable, ",
           "not fungible, ",
           "not verifiable, ",
           "not divisible, ",
           "and hard to transfer. ",
           "But tell me more about your analogy...",
           "-[Naval Ravikant](")

pattern <- c("not" = "extremely",
             "hard" = "ridiculously easy",
             "^But.*" = "So... flower power?",
             "(^-).*Naval.*" = "\\1\U0001F92A")

yay::str_replace_verbose(string = input,
                         pattern = pattern,
                         n_context_chrs = 5L) |>

yay::str_replace_verbose(string = input,
                         pattern = pattern,
                         n_context_chrs = 0L) |>

salim-b/yay documentation built on May 17, 2024, 5:24 a.m.