How to escape a question mark in R?

2020-02-06 05:38发布

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 '?'

标签: regex r
4条回答
成全新的幸福
2楼-- · 2020-02-06 05:52

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.

查看更多
家丑人穷心不美
3楼-- · 2020-02-06 05:56

You have to escape \ as well:

vectorOfStrings <- c("Where is Waldo?", "I don't know", "This is ? random ?")
grep("\\?", vectorOfStrings)
#-----
[1] 1 3
查看更多
劫难
4楼-- · 2020-02-06 05:56

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

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

grep('\\?',vectorofStrings)
grep('?',vectorofStrings, fixed=TRUE)
查看更多
欢心
5楼-- · 2020-02-06 05:59

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

查看更多
登录 后发表回答