3
 a = list("a","b","cdef", "[")
 grep("a",a)
 #[1] 1
 grep("[",a)
 #Error during wrapup: invalid regular expression '[', reason 'Missing ']''
 grep('\[',a)
 #Error during wrapup: '\[' is an unrecognized escape in character string starting "'\["
 grep("\[",a)
 #Error during wrapup: '\[' is an unrecognized escape in character string starting ""\["
 grep("\133",a)
 #Error during wrapup: invalid regular expression '[', reason 'Missing ']''

I thought to do the "\133" based on information found here: http://cran.r-project.org/doc/manuals/R-lang.html#Literal-constants unfortunately it didn't work.

kpie
  • 9,588
  • 5
  • 28
  • 50
  • 1
    did you search? [here](http://stackoverflow.com/questions/27721008/how-do-i-deal-with-special-characters-like-in-my-regex) or [here](http://stackoverflow.com/questions/12695879/error-r-is-an-unrecognized-escape-in-character-string-starting-c-r) or [here](http://stackoverflow.com/questions/10605485/an-error-is-an-unrecognized-escape-in-character-string-starting-while) – rawr Feb 23 '15 at 21:48
  • 2
    There is a remaining question regarding why you are using a pattern that will match none of your test items. – IRTFM Feb 23 '15 at 21:54
  • It makes sense now... Sorry about that. – kpie Feb 23 '15 at 22:39

1 Answers1

5

By default grep() uses regular expressions and [ is a special character in regular expression, you can either disable regular expressions with

grep("[", a, fixed=TRUE)

or escape the [ by doing

grep("\\[", a)

Note the double slash here because the correct regular expression syntax would be \[ but you also need to escape the slash in the R string since you want a literal slash and not an escape code so it becomes \\[

MrFlick
  • 195,160
  • 17
  • 277
  • 295