Here is a simple 1-line solution similar to Zelazny's but using a replace callback method inside a gsubfn
using gsubfn
library:
> library(gsubfn)
> v <- c("Smth1", "Smth22", "Smth333", "Smth4444", "Smth55555")
> gsubfn('[0-9]+$', ~ sprintf("%05d",as.numeric(x)), v)
[1] "Smth00001" "Smth00022" "Smth00333" "Smth04444" "Smth55555"
The regex [0-9]+$
(see the regex demo) matches 1 or more digits at the end of the string only due to the $
anchor. The matched digits are passed to the callback (~
) and sprintf("%05d",as.numeric(x))
pads the number (parsed as a numeric with as.numeric
) with zeros.
To only modify strings that have 1+ non-digit symbols at the start and then 1 or more digits up to the end, just use this PCRE-based gsubfn
:
> gsubfn('^[^0-9]+\\K([0-9]+)$', ~ sprintf("%05d",as.numeric(x)), v, perl=TRUE)
[1] "Smth00001" "Smth00022" "Smth00333" "Smth04444" "Smth55555"
where
^
- start of string
[^0-9]+\\K
- matches 1+ non-digit symbols and \K
will omit them
([0-9]+)
- Group 1 passed to the callback
$
- end of string.