[R] grep pattern

David Winsemius dwinsemius at comcast.net
Sat May 21 01:09:24 CEST 2011


On May 20, 2011, at 11:57 AM, Kang Min wrote:

> Hi all,
>
> I'm trying to subset a pattern in a vector. Each argument has 6
> letters, and I need those that start with Z and end with Z.
>
> e.g.
> x <- c("ZFHSJK", "ZFHJKZ","ZIOPWE","ZLKJSD","ZKFLPZ")
>
> I've looked up other discussions but still can't seem to find the
> answer.

You may need to study the regex page a bit longer

the "^" is the beginning of a string
".+" will math can arbitrarily long string of anything
and "$" indicates the end of a string

 > x <- c("ZFHSJK", "ZFHJKZ","ZIOPWE","ZLKJSD","ZKFLPZ")
 > grep("^Z.+Z$", x)
[1] 2 5
 > grep("^Z.+Z$", x, value=TRUE)
[1] "ZFHJKZ" "ZKFLPZ"


>
> Thanks.
> Kangmin
>
> ______________________________________________
> R-help at r-project.org 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list