I have a list of strings of this kind:
f<-c("CC 982","RX 112","TR 002","FF 1328")
I need to add a leading 0, as with the str_pad
function, at the beginning of the numerical portion, to get to this:
"CC 0982" "RX 0112" "TR 0002" "FF 1328"
For now, I have tried with sub
sub('(.{2})(.{1})(.{3})', "\\1\\20\\3", f)
Close enough, but I don't want the leading 0 if the numerical string has 4 digits. What is the solution here? Thank you
Using sub
you could modify to
sub("(\\D*)(\\b\\d{1,3}\\b)", "\\10\\2", f)
# [1] "CC 0982" "RX 0112" "TR 0002" "FF 1328"
This will only catch numbers up until 3 digits and modify them
We can split the string by space and then use sprintf
to join the components
d1 <- do.call(rbind, strsplit(f, "\\s+"))
sprintf("%s %04d", d1[,1], as.numeric(d1[,2]))
#[1] "CC 0982" "RX 0112" "TR 0002" "FF 1328"
Or with gsubfn/sprintf
we get the expected output
library(gsubfn)
gsubfn("(\\d+)", ~sprintf("%04d", as.numeric(x)), f)
#[1] "CC 0982" "RX 0112" "TR 0002" "FF 1328"
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