re2_replace: Replace matched pattern in string

View source: R/RcppExports.R

re2_replaceR Documentation

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)

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.

Value

A character vector with replacements.

See Also

re2_regexp for options to regular expression, re2_syntax for regular expression syntax.

Examples

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)

re2 documentation built on May 29, 2024, 6:40 a.m.