0

I need a way where gsub (or any other string replacement function) will only replace instances where the entire string is present but nothing else.

e.g.:

String1 <- "FullCosts."
String2 <- "Costs."

Var1 <- "c."

gsub(pattern = String2, replacement = Var1, x = String1)
[1] "FullCosts."

gsub(pattern = String2, replacement = Var1, x = String2)
[1] "c."

instead of what I get at the moment:

gsub(pattern = String2, replacement = Var1, x = String1)
[1] "Fullc."

gsub(pattern = String2, replacement = Var1, x = String2)
[1] "c."

I've also tried playing around with perl = TRUE but to no success:

gsub(pattern = paste0("\\<",String2,"\\>"), replacement = Var1, x = String1, perl = TRUE)
[1] "FullCosts."

gsub(pattern = paste0("\\<",String2,"\\>"), replacement = Var1, x = String2, perl = TRUE)
[1] "Costs."
Shawn
  • 47,241
  • 3
  • 26
  • 60
anallaser
  • 23
  • 4
  • 2
    `gsub(pattern = paste0("^", String2, "$"), replacement = Var1, x = String1)`, but you also need to [escape](https://stackoverflow.com/questions/14836754/is-there-an-r-function-to-escape-a-string-for-regex-characters) `String2` in the regex pattern. – Wiktor Stribiżew Feb 17 '20 at 13:12
  • That's the ticket, cheers! – anallaser Feb 17 '20 at 13:14

0 Answers0