I want to harmonize strings by replacing all trailing Xs and Ys with underscores. Since the length of those strings varies, I wrote the following regex which works fine. However, the first two characters should always stay as they are. I know that I could use substr() and paste0() as a workaround but how can I include this "do not replace the first two characters" in the regex?
x <- c("AXZ", "AZXYYX", "HZX_Y", "BXX", "XYX_")
# replaces all trailing X / Y
gsub("[XY](?=[XY_]*$)", "_", x, perl = TRUE)
#> [1] "AXZ" "AZ____" "HZ___" "B__" "____"
# blocks first character
gsub("(?<!^)[XY](?=[XY_]*$)", "_", x, perl = TRUE)
#> [1] "AXZ" "AZ____" "HZ___" "B__" "X___"
# desired output
c("AXZ", "AZ____", "HZ___", "BX_", "XY__")
#> [1] "AXZ" "AZ____" "HZ___" "BX_" "XY__"
I already managed to exclude the first letter so I guess it should be an easy fix.