Actually, Greg and you already mentioned the cleanest solution. I would generally dump grep altogether:
> name <- "a#" > string <- c("a#b", "cac", "sss", "ca#f") > string[substring(string, 1, nchar(name)) == name] [1] "a#b"
But if you really insist on grep, you can use the Dwins approach or follow the mindboggling solution:
specialgrep <- function(x,y,...){ grep( paste("^", gsub("([].^+?|[#\\-])","\\\\\\1",x) ,sep=""), y,...) } > specialgrep(name,string,value=T) [1] "a#b"
Perhaps I forgot to include some characters in gsub. Make sure you save the character], and the last one in the character set, otherwise you will get errors. Or just forget about it, use your own solution. This is just for fun :-)
source share