[R] About grep

Vladimir Eremeev wl2776 at gmail.com
Tue Aug 7 08:41:11 CEST 2007

Shao wrote:
> Hi,everyone.
> I have a problem when using the grep.
> for example:
> a <- c("aa","aba","abac")
> b<- c("ab","aba")
> I want to match the whole word,so
> grep("^aba$",a)
> it returns 2
> but when I used it a more useful way:
> grep("^b[2]$",a),
> it doesn't work at all, it can't find it, returning integer(0).
> How can I chang the format in the second way?
> Thanks.
The regexp "^b[2]$" matches only two words: "b2" and "b" (in your present
grep call with defaults
extended = TRUE,  perl = FALSE, fixed = FALSE).

They don't present in a, that's why grep returns integer(0).
If you want to find the word "b[2]" (the expression similar to an array
indexing operator), either use fixed=TRUE and remove any regexp markup (^
and $)

> a<- c("aa","aba","abac","b[2]")
> grep("b[2]",a,fixed=TRUE)
[1] 4

, or use escapes

> grep("^b\\[2\\]$",a)
[1] 4

View this message in context: http://www.nabble.com/About-grep-tf4228021.html#a12029243
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list