user6539518 user6539518 - 3 months ago 18
R Question

R gsub word in string beginning with prefix without removing prefix

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 want to it to end up as:

"I am going to buy an 'pear' and a 'pear'"


I've tried a few things like this below but it only ever seems to replace 'apple' and the single quotes, whereas I want to keep the single quotes.

a2 <- gsub("\'apple\'", repl, a)

Answer

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)
# [1] "I am going to buy an 'pear' and a 'pear'"
Comments