2013-07-02 128 views
3

我想查找包含以下向量中的星号的元素。使用特殊字符grep

s <- c("A","B","C*","D","E*") 
grep("*",s) 

[1] 1 2 3 4 5 

这是行不通的。我可以理解,因为它是一个特殊的字符。
当我读here时,我决定在星号之前使用“\”。但这给了我一个错误:

grep("\*",s) 
Error: '\*' is an unrecognized escape in character string starting ""\*" 

我在做什么错了?

回答

7

您需要的正则表达式两次特殊字符转义,一次为R和一次:

grep('\\*', s) 
+0

完美。谢谢.. – HBat

6

另一种选择是使用fixed=TRUE

grep('*', s,fixed=TRUE)