4

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

loki
  • 9,816
  • 7
  • 56
  • 82
AVal
  • 617
  • 2
  • 7
  • 12

2 Answers2

6

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

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
5

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"
akrun
  • 874,273
  • 37
  • 540
  • 662