Numbers don't lie

 
Gadgets

Authentication
Crypto
ENV
HTTP
Regex
Regex 2
Robots
Snarfs
SSL
Stepper

Start with the easiest: a numeric field. What should it include? If you say only digits, then it's simple: match on digits.

if ($string_to_test =~ m/^\d*$/) {
do something here...
}

This fragment looks for 0 to any string of digits from the beginning to the ending of the string. But, what about commas, as in 1,000? OK, add them, and periods, too because we want floating point numbers:

if ($string_to_test =~ m/^[\d,\.]*$/) {
do something here...
}

Come to think of it, though, this code will match 1,2,3,4,5, which we'd probably want to reject. We need to arrange the commas into a regular pattern, and make them optional. The same with the floating point.

if ($string_to_test =~ m/^\d{0,3},?\d{3},?\d{3},?\.?\d*$/) {
do something here...
}

This works OK for numbers up to 999,999,999 and fractions thereof, but what about 1,000,000,000? We could accept the limit, and just add more \d{3},? groups, but why not make it totally flexible?

if ($string_to_test =~ m/^\d{0,3},?(\d{3},?)*\d{3}\.?\d*?/) {
do something here...
}

Note that we need a zero to 3 length group on the front, and a group with a point instead of a comma on the back. This works for comma grouped and non-comma-grouped numeric strings. If you want to limit it to (American) currency, make the trailing decimal optional or 2 digits.

if ($string_to_test =~ m/^\d{0,3},?(\d{3},?)*\d{3}(\.\d{2})?$/) {
do something here...
}

This is useable code, but there's still a flaw. Can you spot it?

<< Back  Next >>






Home | Gadgets | Code | Links | Reads | Contact

Copyright © 1999, 2001, 2002 by John H. Byrd
All rights reserved.