Home: Perl Programming Help: Regular Expressions:
RE for number with or w/o comma



ejaggers1
Novice

Jun 22, 2010, 7:59 AM


Views: 7835
RE for number with or w/o comma

How can you match a number string that may or may not have commas? i.e 123 or 1,234 or 123,456,789...


rovf
Veteran

Jun 23, 2010, 2:55 AM


Views: 7813
Re: [ejaggers1] RE for number with or w/o comma

Using the ?-Quantifier.

From perlre:


Quantifiers

The following standard quantifiers are recognized:

* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times



Zhris
Enthusiast

Jun 23, 2010, 9:09 PM


Views: 7763
Re: [ejaggers1] RE for number with or w/o comma

A basic expression which would allow commas to occur anywhere in the number string:

m/^[0-9,]+$/

Or an untested expression which would allow a comma after the first number or not, then after every 3 numbers or not, although it would allow i.e. "1,234,56789,444":

m/^\d\,?(\d{1,2}|\d{3}\,?)*$/

Sometimes I wonder if it would be easier to validate that the string contains just numbers or commas, remove all commas, then use sprintf to replace the commas in their proper places.

Chris


(This post was edited by Zhris on Jul 25, 2010, 6:31 AM)


ejaggers1
Novice

Jun 24, 2010, 5:34 AM


Views: 7729
Re: [Zhris] RE for number with or w/o comma

Thanks Chris.....That was a BIG help!!!