I'm Sure There's A Better Way

Bengt Richter bokr at accessone.com
Sun Jul 8 02:59:27 CEST 2001


On Sat, 7 Jul 2001 09:38:20 +0200, "Alex Martelli" <aleaxit at yahoo.com>
wrote:

>"Tim Daneliuk" <tundra at tundraware.com> wrote in message
>news:3B465858.CB7F38E8 at tundraware.com...
>> I want a function to check a string to make sure it is a legitimate
>> dollar amount.  Which means it follows these rules:
>>
>> First character is numeric or "-"
>> At most, one "." is allowed and, if present, is followed by exactly two
>digits
>> All the remaining characters must be in the range "0" - "9"
>
>These specs seem to be equivalent to:
>    optional: -
>    one or more digits
I took it to be zero or more
>    optional: . followed by two digits
>    end of string
>
>This is very easy to express as a Regular Expression:
>    r'-?\d+(\.\d\d)?$'
or
     r'^-?(\d*\.\d\d|\d+)$'
if you want to allow .12  (or -.00), see below ;-)
>
>So one function to check any string to see if it satisfies
>this pattern is:
>
>def isDollar(astring):
>    import re
>    return re.match(r'-?\d+(\.\d\d)?$', astring)
>
I had the same idea, except I didn't realize match didn't need
a '^' to anchor at the beginning (!RTFM). And of course my
group()==originalString check was mindless ;-)

Actually, any minus-zero patterns don't seem reasonable,
and other than a single zero, a zero leading digit seems bad,
wherther followed by \.\d\d or not.

I just RTFM'd a little and found the (? extensions. Whee!

r'(-(?!(0*\.?0+$|0+\.0*$)))?(0|\d?\.\d\d|[1-9]\d*(\.\d\d)?)$'




More information about the Python-list mailing list