Mona Mona - 1 month ago 6x
R Question

Insert characters into a string using R

I would like to insert a colon characters once, twice or three times in a string. For example I want

G*2413 => G*24:13
G*15122 => G*15:122
G*010101 => G*01:01:01
G*02010102 => G*02:01:01:02

How can I do this using R?

have <- c('G*2413', 'G*15122', 'G*010101', 'G*02010102')
want <- c('G*24:13', 'G*15:122', 'G*01:01:01', 'G*02:01:01:02')


We can also use a positive lookaround

gsub("(\\d{2})(?=\\d{2})", "\\1:", have, perl = TRUE)
#[1] "G*24:13"       "G*15:122"      "G*01:01:01"    "G*02:01:01:02"