Search code examples
rstringr

How to replace all occurrences of a certain character, but not if the character is the first in string?


I have the following vector

x = c("AXX", "XAX", "XXA")

I would like to replace all the "A" to "B" in x, but not if "A" is at the beginning of the string. Desired:

c("AXX", "XBX", "XXB")

Solution

  • Use a negated start anchor in a regular expression:

    x <- c("AXX", "XAX", "XXA")
    

    Base R

    gsub("(?!^)A", "B", x, perl=TRUE)
    ##[1] "AXX" "XBX" "XXB"
    

    stringr

    library(stringr)
    str_replace_all(x, "(?!^)A", "B")
    ##[1] "AXX" "XBX" "XXB"