Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex to add leading zeroes

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.

like image 410
hpique Avatar asked Apr 17 '10 16:04

hpique


People also ask

What does regex 0 * 1 * 0 * 1 * Mean?

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.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do you add leading zeros to integers?

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.

What does add leading zeros mean?

Leading zeros are used to make ascending order of numbers correspond with alphabetical order: e.g., 11 comes alphabetically before 2, but after 02.


1 Answers

In Perl:

s/([0-9]+)/sprintf('%04d',$1)/ge; 
like image 177
Snowhare Avatar answered Oct 03 '22 20:10

Snowhare