Using more than nine back references in an R regex

半城伤御伤魂 提交于 2019-12-21 21:32:39

问题


The code below does not work, because the replacement string for \10, \11, and so on, cannot be read properly. It reads \10 as \1 and print 0 instead, can you help me fix it? There is an answer in one of the threads, saying that I am supposed to use capturing or naming groups, but I don't really understand how to use them.

headline <- gsub("regexp with 10 () brackets",
"\\1 ### \\2 ### \\3 ### \\4 ### \\5 ### \\6 ### \\7 ### \\8 ### \\9 ###
\\10### \\11### \\12### \\13### \\14### \\15### \\16",
page[headline.index])

回答1:


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"



回答2:


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



来源:https://stackoverflow.com/questions/8321081/using-more-than-nine-back-references-in-an-r-regex

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