grep with special characters

前端 未结 3 591
慢半拍i
慢半拍i 2021-01-12 13:47

I want to find the elements that contains star character in the following vector.

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

[1] 1 2 3 4 5


        
相关标签:
3条回答
  • 2021-01-12 14:20

    You need to escape special characters twice, once for R and once for the regular expression:

    grep('\\*', s)
    
    0 讨论(0)
  • 2021-01-12 14:20

    You may want to see this link, see https://r.789695.n4.nabble.com/Why-do-my-regular-expressions-require-a-double-escape-to-get-a-literal-td4437962.html. As Berend Hasselman mentioned:

    you need the \\ because the expression between tour quotes is interpreted twice.

    0 讨论(0)
  • 2021-01-12 14:21

    Another option is to use fixed=TRUE

    grep('*', s,fixed=TRUE)
    
    0 讨论(0)
提交回复
热议问题