14

I am trying to grep a vector of strings and some of them contain question marks.

I am doing:

grep('\?',vectorofStrings) and getting this error:

Error: '\?' is an unrecognized escape in character string starting "\?"

How can I determine the proper escaping procedure for '?'

pedrosaurio
  • 4,708
  • 11
  • 39
  • 53

4 Answers4

25

You have to escape \ as well:

vectorOfStrings <- c("Where is Waldo?", "I don't know", "This is ? random ?")
grep("\\?", vectorOfStrings)
#-----
[1] 1 3
Chase
  • 67,710
  • 18
  • 144
  • 161
12

Use the \\ or fixed = TRUE argument as in:

vectorofStrings <-c("hello.", "where are you?",  "?")

grep('\\?',vectorofStrings)
grep('?',vectorofStrings, fixed=TRUE)
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
5

I'd guess \ is used in R as a normal string escape character, so to pass a literal \ to grep you might need \\?

Joey
  • 344,408
  • 85
  • 689
  • 683
0

I didn't have luck with backslash escaping, under windows grep. But I managed to make it work by the following:

grep [?]{3} *

That is, I enclosed the question mark in character class brackets ( [ and ] ), which made the special meaning inactive. The {3} part is not relevant to the question, I used it to find 3 consecutive question marks.

Jarekczek
  • 7,456
  • 3
  • 46
  • 66