In R How do I grep something which has a $ in string. In This below example I need to grep string "NB6106$MU-MU.rma"
x<-c("NB6106$MU-MU.rma", "NB610634$MU-MU.rma")
x[grep(pattern="*6106$*.rma", x = x)] #does not work
You may use
x<-c("NB6106$MU-MU.rma", "NB610634$MU-MU.rma")
x[grep(pattern="6106\\$.*\\.rma", x = x)]
See the R demo
Details
6106\\\\$
- 6106$
substring .*
- any 0+ chars \\\\.rma
- a .rma
substring If you plan to make sure you do not grep 11116106$...rma
, you may use
"(^|\\D)6106\\$.*\\.rma$"
where (^|\\\\D)
matches start of string ( ^
) or ( |
) a non-digit char ( \\D
), and $
at the end ensure the end of string appears right after .rma
.
You need to escape it. $ by itself in a regular expression indicates the end of the string, so you need to tell R that here you mean it literally as a $, which is done by escaping. The escape character is \\
. So, in theory, you'll type in \\$
. BUT, since you're writing the pattern as a literal string (within quotes), you ALSO need to escape the escape character, so that R knows to transfer it literally to the regex interpretor. Hence: \\\\$
.
Other issues with your code: * doesn't mean "any characters". It means "repeat the previous character zero or more times". .
means any character, and .*
means any number of any character, which is what you're looking for. And of course, if you want a literal period, you need to escape that too: \\\\.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.