Applying a function to a backreference within gsub in R

后端 未结 4 1353
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 23:19

I\'m new to R and am stuck with backreferencing that doesn\'t seem to work. In:

gsub(\"\\\\((\\\\d+)\\\\)\", f(\"\\\\1\"), string)

It corre

4条回答
  •  生来不讨喜
    2020-12-04 00:10

    This is for multiple different replacements.

    text="foo(200) (300)bar (400)foo (500)bar (600)foo (700)bar"
    
    f=function(x)
    {
      return(as.numeric(x[[1]])+5)
    }
    a=strsplit(text,"\\(\\K\\d+",perl=T)[[1]]
    
    b=f(str_extract_all(text,perl("\\(\\K\\d+")))
    
    paste0(paste0(a[-length(a)],b,collapse=""),a[length(a)])  #final output
    #[1] "foo(205) (305)bar (405)foo (505)bar (605)foo (705)bar"
    

提交回复
热议问题