Learn R Programming

re2 (version 0.1.3)

re2_replace: Replace matched pattern in string

Description

re2_replace replaces the first match of "pattern" in "string" with "rewrite" string.


  re2_replace("yabba dabba doo", "b+", "d")

will result in "yada dabba doo".

re2_replace_all replaces successive non-overlapping occurrences of "pattern" in "text" with "rewrite" string.


  re2_replace_all("yabba dabba doo", "b+", "d")

will result in "yada dada doo".
Replacements are not subject to re-matching. Because re2_replace_all only replaces non-overlapping matches, replacing "ana" within "banana" makes only one replacement, not two.

Vectorized over string and pattern.

Usage

re2_replace(string, pattern, rewrite)

re2_replace_all(string, pattern, rewrite)

Value

A character vector with replacements.

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.

Examples

Run this code
string <- c("yabba dabba doo", "famabbb sb")
re2_replace(string, "b+", "d")
re2_replace_all(string, "b+", "d")

# Rearrange matching groups in replaced string
re2_replace(
  "boris@kremvax.ru",
  "(.*)@([^.]*)", "\\2!\\1"
)

# Use complied pattern
string <- "the quick brown fox jumps over the lazy dogs."
re <- re2_regexp("(qu|[b-df-hj-np-tv-z]*)([a-z]+)")
rewrite <- "\\2\\1ay"
re2_replace(string, re, rewrite)
re2_replace_all(string, re, rewrite)

string <- "abcd.efghi@google.com"
re <- re2_regexp("\\w+")
rewrite <- "\\0-NOSPAM"
re2_replace(string, re, rewrite)
re2_replace_all(string, re, rewrite)

string <- "aba\naba"
re <- re2_regexp("a.*a")
rewrite <- "(\\0)"
re2_replace(string, re, rewrite)
re2_replace_all(string, re, rewrite)

# Vectorize string and pattern
string <- c("ababababab", "bbbbbb", "bbbbbb", "aaaaa")
pattern <- c("b", "b+", "b*", "b*")
rewrite <- "bb"
re2_replace(string, pattern, rewrite)
re2_replace_all(string, pattern, rewrite)

Run the code above in your browser using DataLab