regex - Regular expression to add 0s to beginning of string -
this question has answer here:
- adding leading zeros using r 7 answers
i'm new regular expressions , i'm have trouble putting them @ moment. i'm working r @ moment, , i'm looking ensure strings in character vector of length 3.
so have character vector of following:
['1','23','113']
what regular expression able use ensure length of each string 3
, in cases less, add 0's start?
so output looking be:
['001','023','113']
an explanation alongside answer appreciated, thanks.
edit: length of strings in character vector greater or equal 1 , less or equal 3.
instead of regex, @ sprintf
function:
x <- c(1, 23, 113) x # [1] 1 23 113 sprintf("%03d", x) # [1] "001" "023" "113"
as dealing character vector, need use as.numeric
first:
x <- as.character(x) sprintf("%03d", x) ## won't work # error in sprintf("%03d", x) : # invalid format '%03d'; use format %s character objects sprintf("%03d", as.numeric(x)) # [1] "001" "023" "113"
Comments
Post a Comment