Grep with special characters

I want to find elements that contain the star symbol in the next vector.

s <- c("A","B","C*","D","E*") grep("*",s) [1] 1 2 3 4 5 

This does not work. I can understand this because it is a special character.
When I read here , I decided to use the "\" before the star. But this gave me an error:

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

What am I doing wrong?

+4
source share
2 answers

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

 grep('\\*', s) 
+8
source

Another option is to use fixed=TRUE

 grep('*', s,fixed=TRUE) 
+6
source

Source: https://habr.com/ru/post/1489360/


All Articles