Using more than nine back references in an R regex

女生的网名这么多〃 提交于 2019-12-04 15:07:59

According to ?regexp, named capture has been available in regexpr() and gregexpr() since R-2.14.0. Unfortunately, it is not yet available for sub() or, it turns out, gsub(). So, it may still be useful to you, but will probably require a bit more legwork than you might have hoped.

(For a few examples of naming groups in action, see the examples section of ?regexpr.)

ADDED LATER, FOLLOWING GREG SNOW'S ANSWER

Greg Snow alluded to the possibility of doing this with the gsubfn package. Here's an example that shows that gsubfn() can indeed handle more than nine backreferences:

require(gsubfn)
string <- "1:2:3:4:5:6:7:8:9:10:11"
pat <- "^(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+:(\\d)+"
gsubfn(pat, ~ paste(a,b,c,d,e,f,g,h,i,j,k,j,i,h,g,f,e,d,c,e,a), string)  
# [1] "1 2 3 4 5 6 7 8 9 10 11 10 9 8 7 6 5 4 3 5 1"

You might consider using gsubfn from the gsubfn package instead of gsub, it gives more options on how to create your replacement.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!