Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of "&" in R's regular expressions for backreference to entire match?

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)?

like image 960
crazybilly Avatar asked Aug 01 '16 18:08

crazybilly


People also ask

Do you say equivalent of or to?

The adjective equivalent is used when something has the same value, amount, meaning etc. as another thing. The most common preposition used with this adjective is to: 150 grams are equivalent to a medium-sized potato.

What is the of equivalent?

Definition of equivalent 1 : equal in force, amount, or value also : equal in area or volume but not superposable a square equivalent to a triangle. 2a : like in signification or import. b : having logical equivalence equivalent statements. 3 : corresponding or virtually identical especially in effect or function.

What is an example of equivalent?

The definition of equivalent is something that is essentially the same or equal to something else. An example of equivalent is (2+2) and the number 4. Since 2+2= 4, these two things are equivalent. To make equivalent to; to equal.


1 Answers

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"
like image 60
Wiktor Stribiżew Avatar answered Sep 28 '22 00:09

Wiktor Stribiżew