I'm trying to use gsub to replace a word within a string (that's contained in single quotes, i.e. beginning and ending with a single quote) with a different word, that is stored in a variable. I want to keep the single quotes.
So if I start with this:
a <- "I am going to buy an 'apple' and a 'apple'"
repl <- "pear"
"I am going to buy an 'pear' and a 'pear'"
a2 <- gsub("\'apple\'", repl, a)
You can use
?<= look behind and
?= look ahead syntax in the
Perl-compatible regexps as from
?gsub, in which case the single quote will just act like boundary but won't be replaced:
gsub("(?<=\')apple(?=\')", repl, a, perl = T) #  "I am going to buy an 'pear' and a 'pear'"