I would like to insert a colon every five characters starting from the end of the string, preferably using regex and gsub in R.
text <- "My Very Enthusiastic Mother Just Served Us Noodles!"
I have been able to insert a colon every five characters from beginning of the text using:
gsub('(.{5})', "\\1:", text, perl = T)
I have written an inelegant function for achieving this as follows:
library(dplyr)
str_reverse<-function(x){
strsplit(x,split='')[[1]] %>% rev() %>% paste(collapse = "")
}
text2<-str_reverse(text)
text3<-gsub('(.{5})', "\\1:", text2, perl = T)
str_reverse(text3)
to get the desired result
[1] "M:y Ver:y Ent:husia:stic :Mothe:r Jus:t Ser:ved U:s Noo:dles!"
Is there a way this can be achieved directly using regular expressions?