[R] Perl-style regexes and capturing results

Gabor Grothendieck ggrothendieck at gmail.com
Thu May 4 15:56:26 CEST 2006


gsub and sub support backreferences

sub("(.):(.)", "\\2:\\1", c("1:2", "5:6")) # c("2:1", "6:5")

# and you can capture them separately using strapply in the gsubfn package
# or perform function-based substitutions using gsubfn.

# Returns: list(c("1", "2"), c("5", "6"))

library(gsubfn)
strapply(c("1:2", "5:6"), "(.):(.)", function(z,x,y) c(x,y))

# same
strapply(c("1:2", "5:6"), "(.):(.)", c, backref = -2)



On 5/4/06, Sean Davis <sdavis2 at mail.nih.gov> wrote:
> Just a quick question....
>
> In perl, I can capture parts of a regex like /(\w)\/(\d)/ to get back $1 and
> $2 containing the parts of the regex in parentheses.  Is there a parallel in
> R?
>
> Thanks,
> Sean
>
> ______________________________________________
> 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
>




More information about the R-help mailing list