14

我正在尝试 grep 字符串向量,其中一些包含问号。

我在做:

grep('\?',vectorofStrings) 并收到此错误:

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

如何确定“?”的正确转义过程

4

4 回答 4

24

你也必须逃跑\

vectorOfStrings <- c("Where is Waldo?", "I don't know", "This is ? random ?")
grep("\\?", vectorOfStrings)
#-----
[1] 1 3
于 2012-05-15T14:04:26.393 回答
11

使用\\orfixed = TRUE参数,如:

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

grep('\\?',vectorofStrings)
grep('?',vectorofStrings, fixed=TRUE)
于 2012-05-15T14:06:08.823 回答
5

我猜\它在 R 中用作普通的字符串转义字符,因此将文字传递\grep您可能需要\\?

于 2012-05-15T14:04:43.533 回答
0

在 windows grep 下,我没有反斜杠转义的运气。但我设法通过以下方式使其工作:

grep [?]{3} *

也就是说,我将问号括在字符类括号([])中,这使得特殊含义无效。该{3}部分与问题无关,我用它找到了3个连续的问号。

于 2014-10-29T12:51:51.527 回答