以前缀开头的字符串中的R gsub单词而不删除前缀

R gsub word in string beginning with prefix without removing prefix

我正在尝试使用 gsub 将字符串中的单词(包含在单引号中,即以单引号开头和结尾)替换为存储在变量中的不同单词。我想保留单引号。

所以如果我从这个开始:

a <- "I am going to buy an 'apple' and a 'apple'"
repl <- "pear"

我希望它最终成为:

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

我在下面尝试了一些类似的方法,但它似乎只能替换 'apple' 和单引号,而我想保留单引号。

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

?gsub 开始,您可以在 Perl-compatible regexps 中使用 ?<= look behind 和 ?= look ahead 语法,在这种情况下,单引号就像边界一样但不会被替换:

gsub("(?<=\')apple(?=\')", repl, a, perl = T)
# [1] "I am going to buy an 'pear' and a 'pear'"

使用gsubfn

library(gsubfn)
gsubfn("'([^']+)'", paste0("'", repl, "'"), a)
#[1] "I am going to buy an 'pear' and a 'pear'"