是否可以在 R 中转义“[”
Is it possible to escape "[" in R
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("3",a)
#Error during wrapup: invalid regular expression '[', reason 'Missing ']''
我想根据此处找到的信息执行“\133”:http://cran.r-project.org/doc/manuals/R-lang.html#Literal-constants不幸的是它没有用。
默认grep()
使用正则表达式,[
是正则表达式中的特殊字符,您可以使用
禁用正则表达式
grep("[", a, fixed=TRUE)
或通过
逃避[
grep("\[", a)
请注意此处的双斜杠,因为正确的正则表达式语法为 \[
但您还需要转义 R 字符串中的斜杠,因为您需要的是文字斜杠而不是转义码,因此它变为 \[
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("3",a)
#Error during wrapup: invalid regular expression '[', reason 'Missing ']''
我想根据此处找到的信息执行“\133”:http://cran.r-project.org/doc/manuals/R-lang.html#Literal-constants不幸的是它没有用。
默认grep()
使用正则表达式,[
是正则表达式中的特殊字符,您可以使用
grep("[", a, fixed=TRUE)
或通过
逃避[
grep("\[", a)
请注意此处的双斜杠,因为正确的正则表达式语法为 \[
但您还需要转义 R 字符串中的斜杠,因为您需要的是文字斜杠而不是转义码,因此它变为 \[