R: change to the same character as the previous character in the string

Suppose I have a vector c('JKA1','BP9C','SSTQ3WA'), and I want to change the character to a number before that very number, so R returns 'JK11' 'B99C' 'SST33WA'. Is there a way to do this with regex, or am I better off using something other than R?

+4
source share
1 answer

Match the letter in front of the number and then write the number through the capture group. Then replace the matching characters with \\1\\1means double the number of characters present inside the group index.

> x <- c('JKA1','BP9C','SSTQ3WA')
> gsub("[A-Za-z](\\d)", "\\1\\1", x)
[1] "JK11"    "B99C"    "SST33WA"

sub for this case will be enough.

> sub("[A-Z](\\d)", "\\1\\1", x)
[1] "JK11"    "B99C"    "SST33WA"
+7
source

All Articles