tags:

views:

118

answers:

4

i have this regular expression: ^\$?(\d{1,3}(\,\d{3})*|(\d+))(.\d{2})?$

however it is failing when i have an amount such as this: 41022095.6

anything i am missing?

+3  A: 

Your regular expression expects either no decimal point, or a decimal point followed by two decimal digits. It depends on what you want, but you could make your regex match your suggested input by doing this:

^\$?(\d{1,3}(\,\d{3})*|(\d+))(\.\d{1,2})?$

I changed the {2} near the end to {1,2} to allow one or two decimal digits after the decimal point. I also changed the . to \. because a plain . in a regex means "match any character".

Greg Hewgill
d'oh! better than mine.
duffymo
Doesn't the leading \$ also requires a dollar sign for the accepted input?
Calyth
Calyth: There's a question mark following the \$.
Greg Hewgill
+1  A: 

doesn't the dot mean "any character", unless it's in brackets?

duffymo
A: 

This part: "(.\d{2})?" says that your number can optionally end in "dot followed by two digits", but it's optional. Since you don't have "dot followed by two digits" anywhere in your example and nothing else that allows a dot, it is not matched.

Also, ass duffymo pointed out, you probably want to escape the dot to make it match the full stop instead of any character.

Joachim Sauer
should still match everything up to the dot. and the dot doesn't match a dot.
Triptych
Yes, everything up to the dot, but since the regex ends in "$" it doesn't actually match unless it matches the *whole string*. Also: A "." in a regex does actually match a "." in the target String (together with a lot of other stuff).
Joachim Sauer
Removed downvote - I missed the '$' at the end.
Triptych
A: 

Try changing that last bit to (.\d{1,2})?. Otherwise it will require 2 digits at the end.

Also, you might want to escape the '.'

Herms
or maybe (.\d{0,2})? in case you want a decimal followed by NO fractional part.
duffymo