Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 326
Maël Avatar asked Mar 12 '26 22:03

Maël


1 Answers

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"
like image 91
Darren Tsai Avatar answered Mar 14 '26 16:03

Darren Tsai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!