For the following string vector s, I hope to remove leading zeros in each elements, which is reverse of the answer from this link:
s <- c('week 01st', 'weeks 02nd', 'year2022week01st', 'week 4th')
The expected result will like:
s <- c('week 1st', 'weeks 2nd', 'year2022week1st', 'week 4th')
I test the following code, it's not working out since the regex syntax is not complete:
s <- 'week 01st'
sub('^0+(?=[1-9])', '', s, perl=TRUE)
sub('^0+([1-9])', '\\1', s)
Out:
[1] "week 01st"
How could I do that using R?
Update: for the following code contributed by @dvantwisk, it works for year2022week01st, but not suitable to other elements:
s <- c('week 01st', 'weeks 02nd', 'year2022week01st', 'week 4th')
gsub('(year[0-9]{4,})(week)(0{0,})([1-9]{1})([0-9a-zA-Z]{1,})', '\\1\\2\\4\\5', s)
Out:
[1] "week 01st" "weeks 02nd" "year2022week1st" "week 4th"