是否有等效的“&"?在 R 的正则表达式中用于反向引用整个匹配? [英] Is there an equivalent of "&" in R's regular expressions for backreference to entire match?

查看:69
本文介绍了是否有等效的“&"?在 R 的正则表达式中用于反向引用整个匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 vim 时,我经常使用 & 在替换中反向引用整个匹配项.例如,以下将所有foo"的实例替换为foobar":

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.

在 R 的正则表达式中是否有与我在 vim 中使用的 & 等效的代码(可能使用 perl = T 参数)?

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

推荐答案

在基础 R sub/gsub 函数中:答案是NO,请参阅此参考:

整体匹配没有替换文本标记.将整个正则表达式放在一个捕获组中,然后使用 \1 插入整个正则表达式匹配.

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.

stringr 包中: 是的,您可以使用 \0:

> library(stringr)
> str_replace_all("123 456", "\\d+", "START-\\0-END")
[1] "START-123-END START-456-END"

这篇关于是否有等效的“&"?在 R 的正则表达式中用于反向引用整个匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆