Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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(x, "(?!^)A", "B")
##[1] "AXX" "XBX" "XXB"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading