Add number in the string after each letter

  • A+
Category:Languages

I have several strings with a fixed format.

The format is one letter followed by a number, e.g., A3B1C7D1.

However, if the number behind a letter is 1, the string is written as A3BC7D.

What I want to do is to insert number 1, and convert the string from A3BC7D to A3B1C7D1.

My example data is

strings <- c("A", "A3BC3", "A2B1C") 

What I want to get is:

strings_new <- c("A1", "A3B1C3", "A2B1C1") 

Thanks a lot!

 


Another option:

gsub("([A-Za-z])(?=[A-Za-z])|([A-Za-z])$", "//1//21", strings, perl = T) 

Output:

[1] "A1"     "A3B1C3" "A2B1C1" 

Or if you only have capitals, just:

gsub("([A-Z])(?=[A-Z])|([A-Z])$", "//1//21", strings, perl = T) 

Basically this finds letters that are either followed by another letter or are at the end of string, and replaces them with themselves while at the same time adds the desired number, 1 in this case.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: