I want to replace a suffix in a string. This suffix can be either .x
or .y
. If its is .x
I want to replace it by string1
(say) if it is .y
it should be replaced by string2
. (the replacement strings are arbitrary, but there is a clear mapping between suffix and replacement string, e.g. .x -> .string1
and .y -> .string2
).
I can easily achieve that by using 2 calls of gsub
like this:
in_str <- c("a.x", "a.y")
gsub("\\.y$", ".string2", gsub("\\.x$", ".string1", in_str)))
# [1] "a.string1" "a.string2"
Question
Is there a regex
with which I can achieve that with just one call of gsub
? Or is there any library function with which I can replace the suffixes in one go?