re2r (version 0.2.0)

re2_replace: Replace matched patterns in a string.

Description

Replace the the first match or all matches of pattern in string with replacement.

Usage

re2_replace(string, pattern, replacement, parallel = FALSE,
  grain_size = 1e+05, ...)

re2_replace_all(string, pattern, replacement, parallel = FALSE, grain_size = 1e+05, ...)

Arguments

string

a character vector

pattern

a pre-compiled regular expression or a string

replacement

replace the first match or all of the match of pattern in string with "rewrite"

parallel

use multithread

grain_size

a minimum chunk size for tuning the behavior of parallel algorithms

...

further arguments passed to re2

Value

For re2_replace, a character vector. For re2_replace_all, a character vector with the number of replacements.

Details

Within replacement, backslash-escaped digits (\1 to \9) can be used to insert text matching corresponding parenthesized group from the pattern. \0 in replacement refers to the entire matching text.

Vectorised over strings, patterns and replacements.

Examples

Run this code
# NOT RUN {
# replace one or more b, prefer more
regexp = re2("b+")
re2_replace_all("yabba dabba doo", regexp,"d")
re2_replace("yabba dabba doo", "b+","d")

# trim string
pattern = "^\\s+|\\s+$"
re2_replace_all(c("  abc  "," this is "), pattern, "")

# mask the middle three digits of a US phone number
texts = c("415-555-1234",
          "650-555-2345",
          "(416)555-3456",
          "202 555 4567",
          "4035555678",
          "1 416 555 9292")

us_phone_pattern = re2("(1?[\\s-]?\\(?\\d{3}\\)?[\\s-]?)(\\d{3})([\\s-]?\\d{4})")

re2_replace(texts, us_phone_pattern, "\\1***\\3")

# show_regex(us_phone_pattern)

# }

Run the code above in your browser using DataLab