Search code examples
rextractdata-manipulationdata-cleaning

grep items with special symbols


I am trying use grep to extract item that contains symbols_ and |. When I tried to grep with exact match, it returned all items. How to solve the problem?

string = c("ny_(apple)|store", "mn_(apple)|store", "ok_(apple)|store")
grep("\\ny_(apple)|store\\>", string) #this failed because it returned all three items
[1] 1 2 3

Solution

  • Use (double) backslash escapes:

    grep("ny_\\(apple\\)\\|store", string)
    #> [1] 1