A user asked me how to do this in How to italicize select words in a ggplot legend?, and I'm not happy with my workaround.
The aim is to add enclosing * around all character vector elements except for given strings. Let's assume for this example that those would always be found at the beginning. I am using an optional capture for the first group and then include the second group with the asterisks. The problem arises when the searched word stands alone and there is no following string.
I've included the desired output and some attempts in the code.
v <- head(rownames(mtcars))
## does also not work with (.*)?, nor with (.+) nor (.+)?
gsub("(Hornet |Valiant)?(.*)", "\\1\\*\\2\\*", v)
#> [1] "*Mazda RX4*" "*Mazda RX4 Wag*" "*Datsun 710*"
#> [4] "Hornet *4 Drive*" "Hornet *Sportabout*" "Valiant**"
## desired output
ifelse(grepl("Valiant", v), v, gsub("(Hornet )?(.*)", "\\1\\*\\2\\*", v) )
#> [1] "*Mazda RX4*" "*Mazda RX4 Wag*" "*Datsun 710*"
#> [4] "Hornet *4 Drive*" "Hornet *Sportabout*" "Valiant"