Search code examples
rstringalphanumeric

Add leading zeros in alphanumeric string


I have a character vector with strings with a similar format (letters, underscore, digits):

v <- c("AB_124", "BAE_1", "LOED_1234", "H_01")

I want to add leading zeroes to have a length of 4 for the numerical part:

c("AB_0124", "BAE_0001", "LOED_1234", "H_0001")

What are ways to do it?


Solution

  • A stringr solution that supplies a function (e.g. str_pad) into str_replace() to replace the match.

    library(stringr)
    
    str_replace(v, "(\\d+)$", ~ str_pad(.x, 4, pad = 0))
    
    # [1] "AB_0124"   "BAE_0001"  "LOED_1234" "H_0001"