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

后端 未结 2 1452
离开以前
离开以前 2021-01-12 19:23

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

相关标签:
2条回答
  • 2021-01-12 20:14

    We can use gsubfn

    library(gsubfn)
    gsubfn("\\d+", ~paste0("START-", x, "-END"), "123 456")
    #[1] "START-123-END START-456-END"
    
    0 讨论(0)
  • 2021-01-12 20:17

    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"
    
    0 讨论(0)
提交回复
热议问题