Suppose I have a vector c('JKA1','BP9C','SSTQ3WA')
and I want to change the character before the number to that very number, so that R returns 'JK11' 'B99C' 'SST33WA'
. Is there anyway to do this with regex or am I better off using something other than R?
Match the letter before the number and then capture the number through capturing group. Then replace the matched characters with \\1\\1
means double times of characters present inside the group index 1.
> x <- c('JKA1','BP9C','SSTQ3WA')
> gsub("[A-Za-z](\\d)", "\\1\\1", x)
[1] "JK11" "B99C" "SST33WA"
sub
function would be enough for this case.
> sub("[A-Z](\\d)", "\\1\\1", x)
[1] "JK11" "B99C" "SST33WA"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With