HBat
HBat

Reputation: 5702

grep with special characters

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

This is not working. I can understand that since it is a special character.
When I read here, I decided to use "\" before star character. But that gave me an error:

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

What am I doing wrong?

Upvotes: 11

Views: 15419

Answers (3)

John Li
John Li

Reputation: 11

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.

Upvotes: 0

agstudy
agstudy

Reputation: 121618

Another option is to use fixed=TRUE

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

Upvotes: 11

Justin
Justin

Reputation: 43265

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

grep('\\*', s)

Upvotes: 16

Related Questions