This does not really answer the specific question you posted but
gsubfn can do it without using \\1 and \\2 like this (you probably
realized that already but I thought I would point it out just in case):
library(gsubfn)
gsubfn("(?<month>\\d+)/(?<day>\\d+)/",
month + day ~ sprintf("%s/%s/", day, month),
British.dates,
backref = -2, British.dates, perl = TRUE)
On 3/7/07, Stefan Th. Gries <stgries_lists at arcor.de>
wrote:> Hi
>
> I have a problem with substitutions involving named backreferences. I
> have a vector American.dates:
>
> > American.dates
> [1] "5/15/1976" "2.15.1970" "1.9.2006"
>
> which I want to change into British.dates:
>
> > British.dates
> [1] "15/5/1976" "15/2/1970" "9/1/2006"
>
> I know I can do it like this:
>
> British.dates<-sub("(\\d{1,2})\\D(\\d{1,2})\\D",
"\\2/\\1/",
> American.dates, perl=T)
>
> But I want to use named backreferences. I was trying something like
> this
>
>
British.dates<-sub("(?P<MONTH>\\d{1,2})\\D(?P<DAY>\\d{1,2})\\D",
> "...", American.dates, perl=T)
>
> but the problem is the ... I know I could use the named backreferences
> *in the search pattern* with (?P=MONTH), but how do I use them *in the
> replacement pattern"? I didn't get the Python solution to work:
>
> >
(British.dates<-sub("(?P<MONTH>\\d{1,2})\\D(?P<DAY>\\d{1,2})\\D",
"'\g<MONTH>\g/\\1/", American.dates, perl=T))
> [1] "'g<MONTH>g/5/1976"
"'g<MONTH>g/2/1970" "'g<MONTH>g/1/2006"
>
> >
(British.dates<-sub("(?P<MONTH>\\d{1,2})\\D(?P<DAY>\\d{1,2})\\D",
"'\\g<MONTH>\\g/\\1/", American.dates, perl=T))
> [1] "'g<MONTH>g/5/1976"
"'g<MONTH>g/2/1970" "'g<MONTH>g/1/2006"
>
> I know I can use the numbers again, but then what would be the point
> of having used names in the first place ...
>
> Any ideas? Thx a bunch,
> STG
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>