[R] Help with grep (and similar functions)

Gabor Grothendieck ggrothendieck at gmail.com
Wed Mar 28 14:51:15 CEST 2007


Try this:

library(gsubfn)
pat <- "([[:upper:]][[:lower:]]*) "
s <- "Aaaa 3 x 0 Bbbb"

strapply(s, pat, backref =-1)[[1]]

or (not quite as general but works in this case):

pat <- "([[:upper:]][[:lower:]]*) "
s <- "Aaaa 3 x 0 Bbbb"

s.idx <- gregexpr(pat, s)[[1]]
substring(s, s.idx, s.idx + attr(s.idx, "match.length") - 2)

On 3/28/07, Alberto Monteiro <albmont at centroin.com.br> wrote:
> This works:
>
> grep("([A-Za-z]*) ", "Aaaa 3 x 0 Bbbb") # 1
>
> This also works:
>
> grep("([A-Za-z]*) ", "Aaaa 3 x 0 Bbbb", value=T) # Aaaa 3 x 0 Bbbb
>
> However, I want a grep that returns the _matched_ pattern, which, in this
> case, would be Aaaa. How can I do it?
>
> Alberto Monteiro
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list