6

When I use vim, I often use & to backreference the entire match within substitutions. For example, the following replaces all instances of "foo" with "foobar":

%s/foo/&bar/g

The benefit here is laziness: I don't have to type the parenthesis in the match and I only have to type one character instead of two for the backreference in the substitution. Perhaps more importantly, I don't have figure out my backrefrences while I'm typing my match, reducing cognitive load.

Is there an equivalent to the & I'm using in vim within R's regular expressions (maybe using the perl = T argument)?

smci
  • 32,567
  • 20
  • 113
  • 146
crazybilly
  • 2,992
  • 1
  • 16
  • 42
  • Beware when you say "in R". There are tons of regex match/replace functions in R: some in `base` package, some in `stringi/stringr`, some elsewhere, etc. The answer depends on the package. – smci Jun 27 '19 at 18:40

2 Answers2

7

In base R sub/gsub functions: The answer is NO, see this reference:

There is no replacement text token for the overall match. Place the entire regex in a capturing group and then use \1 to insert the whole regex match.

In stringr package: YES you can use \0:

> library(stringr)
> str_replace_all("123 456", "\\d+", "START-\\0-END")
[1] "START-123-END START-456-END"
smci
  • 32,567
  • 20
  • 113
  • 146
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

We can use gsubfn

library(gsubfn)
gsubfn("\\d+", ~paste0("START-", x, "-END"), "123 456")
#[1] "START-123-END START-456-END"
akrun
  • 874,273
  • 37
  • 540
  • 662