Add the start 0 to a specific position in line (R)

I have a list of lines like this:

f<-c("CC 982","RX 112","TR 002","FF 1328")

I need to add a start 0, like a function str_pad, at the beginning of the numeric part to go to the following:

"CC 0982" "RX 0112" "TR 0002" "FF 1328"

I have currently tried to use sub

sub('(.{2})(.{1})(.{3})', "\\1\\20\\3", f) 

Close enough, but I don't want the leading 0 if the number string has 4 digits. What is the solution here? Thanks you

+4
source share
2 answers

We can split the line by space and then use sprintfto connect 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/sprintfwe get the expected output

library(gsubfn)
gsubfn("(\\d+)", ~sprintf("%04d", as.numeric(x)), f)
#[1] "CC 0982" "RX 0112" "TR 0002" "FF 1328"
+5
source

Using sub, you can change to

sub("(\\D*)(\\b\\d{1,3}\\b)", "\\10\\2", f)
# [1] "CC 0982" "RX 0112" "TR 0002" "FF 1328"

+6

Source: https://habr.com/ru/post/1683656/


All Articles