x <- c("On the Internet, nobody knows I'm a dog", "On the Internet, '''nobody''' knows I''m a ''''dog''''") gsub("''(*SKIP)(?!)|'", "''", x, perl=TRUE)
Standard input is empty
[1] "On the Internet, nobody knows I''m a dog" [2] "On the Internet, ''''nobody'''' knows I''m a ''''dog''''"