I'm Sure There's A Better Way

Bengt Richter bokr at accessone.com
Sat Jul 7 20:59:27 EDT 2001

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

>"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
>> 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)?$'
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!


More information about the Python-list mailing list