Tuesday, April 14, 2009

Regex to remove leading zeros

Lets learn about a simple regular expression, that will remove all the leading zeros from a given string. This regexp will work for Python, Perl, PHP, and ruby so far I know. But still you can try the regexp with other languages for sure.

The regular expression is:

The above expression will remove all leading zeros. But remember, if the string contains all zeros, for example "0000000" it will remove all zeros, and keep an empty string as returns.

If you want to keep see it 0 after removing all leading zeros from "000000", the Perl regular expression will be as below with an example.
my $string = "0000000";
$string =~ s/^0+(.)/"$1"/e;
print "$string\n";

You know PHP is a bit different to perform regex matching, and replacing. I'm using the same above expression, using preg_replace() of php. Here goes the example that will remove all the leading zeros, but keep single zero, if all are zero.
$string = "0000000";
$string = preg_replace('/^0+(.)/', "$1", $string);
print "$string\n";

So far I don't know how to use the /e modifier of Perl into Ruby or Python. That's why no example of Ruby and Python for second portion. You have to be happy with replacing all zeros with empty :-p, If anyone know this just post here as comment. Will be great if you do. But for sure, I'll find myself soon about how to do it.


chorny said...

You don't need /e here.
$string =~ s/^0+(.)/$1/;

It can also be written as
$string =~ s/^0+(?=.)//;

anshu said...

Please suggest Regex to remove trailing zeroes after .

eg: 1.0 to 1
eg: 1.00 to 1

Anonymous said...

RegEx Cool! Works great!

Kyle said...

Remove leading zeros from an ip address:

find non 3 digit numbers in ip address and add zeros. Helps in sorting the ip addresses in excel:
Finds a single digit in an ip address and tags it at \1
then: 00\1
You could change the {1} to {2} to find the two digit numbers

@ Anshu:
use ([1-9]+) which tags any digit other than zero as \1. Use this in find and replace.

helperpsp at gmail

Namaskaram said...

Can some one tell how to use this in an Xquery

Namaskaram said...

can some one tell me how to use this in an XQuery

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...