in reply to Money Regex

This is what I came up with..
/^\$?(\d+)?\.?\d?\d?$/
Basically, just matches the start of the string followed by an optional dollar sign, followed by one or more optional numbers, followed by an optional period followed by 2 optional numbers. Followed by the end of the string

But, I am by no means a regex expert, this seems to work, I have tested against a file containing lines with letters and numbers, as well as criteria above, but I am sure someone else will point out the glaring errors in the above :-)

Replies are listed 'Best First'.
Re: Re: Money Regex
by flocto (Pilgrim) on Feb 05, 2001 at 17:22 UTC
    I'd just change it a little bit:

    /^\$?\d+(\.\d\d)?$/

    That matches $12, $12.00, $0.12, etc.., but not $12., $.50, $12.013, etc..

    Regards, octopus
    --
    GED/CC d-- s:- a--- C++(+++) UL+++ P++++$ L++>++++ E--- W+++@ N o? K? w-- O- M-(+) V? !PS !PE !Y PGP+(++) t-- 5 X+ R+(+++) tv+(++) b++@ DI+() D+ G++ e->+++ h!++ r+(++) y+
Re: Re: Money Regex
by extremely (Priest) on Feb 06, 2001 at 09:28 UTC
    Uh, as long as you have no problem with it matching "" and "$" and "." that regex will do just fine. If you make everything in a regex optional, you aren't going to get what you really meant very often.

    I'd start with /^\$?(\d+(\.\d{1,2})?|\.\d{1,2})$/ which requires there to be at least one digit before an optional decimal and 1 or 2 digits or that there be a decimal followed by 1 or 2 digits. It is ugly but it works.

    --
    $you = new YOU;
    honk() if $you->love(perl)