是否有可能在R中逃脱“[”

时间:2015-02-23 21:45:07

标签: r escaping

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

我想要做" \ 133"基于此处的信息:http://cran.r-project.org/doc/manuals/R-lang.html#Literal-constants不幸的是它没有用。

1 个答案:

答案 0 :(得分:2)

默认情况下grep()使用正则表达式而[是正则表达式中的特殊字符,您可以使用

禁用正则表达式
grep("[", a, fixed=TRUE)

或通过

逃避[
grep("\\[", a)

请注意这里的双斜杠,因为正确的正则表达式语法将是\[,但您还需要转义R字符串中的斜杠,因为您需要一个文字斜杠而不是转义码,因此它变为{{1 }}