Learn R Programming

re2 (version 0.1.3)

re2_extract_replace: Extract with substitutions

Description

Like re2_replace, except that if the pattern matches, "rewrite" string is returned with substitutions. The non-matching portions of "text" are ignored.

Difference between re2_extract_replace and re2_replace:


> re2_extract_replace("bunny@wunnies.pl", "(.*)@([^.]*)", "\2!\1")
[1] "wunnies!bunny"

> re2_replace("bunny@wunnies.pl", "(.*)@([^.]*)", "\2!\1") [1] "wunnies!bunny.pl"

"\1" and "\2" are names of capturing subgroups.

Vectorized over string and pattern.

Usage

re2_extract_replace(string, pattern, rewrite)

Value

A character vector with extractions.

Arguments

string

A character vector, or an object which can be coerced to one.

pattern

Character string containing a regular expression, or a pre-compiled regular expression (or a vector of character strings and pre-compiled regular expressions).
See re2_regexp for available options.
See re2_syntax for regular expression syntax.

rewrite

Rewrite string. Backslash-escaped digits (\1 to \9) can be used to insert text matching corresponding parenthesized group from the pattern. \0 refers to the entire matching text.

See Also

re2_regexp for options to regular expression, re2_syntax for regular expression syntax. See re2_replace and re2_replace_all to replace pattern in place.

Examples

Run this code
# Returns extracted string with substitutions
re2_extract_replace(
  "bunny@wunnies.pl",
  "(.*)@([^.]*)",
  "\\2!\\1"
)

# Case insensitive
re2_extract_replace(
  "BUNNY@wunnies.pl",
  re2_regexp("(b.*)@([^.]*)", case_sensitive = FALSE),
  "\\2!\\1"
)

# Max submatch too large (1 match group, 2 submatches needed).
#   Replacement fails and empty string is returned.
re2_extract_replace("foo", "f(o+)", "\\1\\2")

Run the code above in your browser using DataLab