I would like to add a certain number of leading zeroes (say up to 3) to all numbers of a string. For example:
Input: /2009/5/song 01 of 12
Output: /2009/0005/song 0001 of 0012
What's the best way to do this with regular expressions?
Edit:
I picked the first correct answer. However, all answers are worth giving a read.
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
$ means "Match the end of the string" (the position after the last character in the string).
You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string.
Leading zeros are used to make ascending order of numbers correspond with alphabetical order: e.g., 11 comes alphabetically before 2, but after 02.
In Perl:
s/([0-9]+)/sprintf('%04d',$1)/ge;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With