Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add number in the string after each letter

Tags:

string

regex

r

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!

like image 641
Wang Avatar asked Feb 22 '19 11:02

Wang


1 Answers

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.

like image 151
arg0naut91 Avatar answered Sep 28 '22 11:09

arg0naut91