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?
If you include special characters in patterns typed on the command line, escape them by enclosing them in single quotation marks to prevent inadvertent misinterpretation by the shell or command interpreter. To match a character that is special to grep –E, put a backslash ( \ ) in front of the character.
5 Searching for Metacharacters. Suppose you want to find lines in the text that have a dollar sign ( $ ) in them. Preceding the dollar sign in the regular expression with a backslash ( \ ) tells grep to ignore (escape) its special meaning.
Grep can identify the text lines in it and decide further to apply different actions which include recursive function or inverse the search and display the line number as output etc. Special characters are the regular expressions used in commands to perform several actions like #, %, *, &, $, @, etc.
The wildcard * (asterisk) can be a substitute for any number of letters, numbers, or characters. Note that the asterisk (*) works differently in grep. In grep the asterisk only matches multiples of the preceding character. The wildcard * can be a substitute for any number of letters, numbers, or characters.
You need to escape special characters twice, once for R and once for the regular expression:
grep('\\*', s)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With