问题
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