tags:

views:

39

answers:

5

hi

can someone please help me to compose a regular expression to check a currency string is in a particular format - 300.00

It can have only numbers both before and after the '.'. However i want only one occurrance of the '.'.

Hence 300.00. or 300.0.0 is invalid.

regards

+2  A: 
^[0-9]+\.?[0-9]*$

This means, beginning of string (^), one or more digits ([0-9]+), optional period (\.?), then 0 or more digits, then the end of the string. You can modify it as needed, e.g. to allow strings beginning with period (change first + to *) or make the period mandatory (remove ?).

Matthew Flaschen
thanks a lot for this.
Kojof
+1  A: 

I think this'll do it: ^\d+\.\d+$

This will match a string that consists of one or more digits, exactly one '.', and one or more digits.

jwismar
+2  A: 

If you want to represent a string that is strictly correct for currency, then you'd most likely want something like ^\d+\.\d{2}$, since you typically represent currency with 2 decimal points. If you're not picky, then ^\d+\.\d+$ will match any number of decimal places or ^\d+\.?\d*$ will match whole numbers as well as numbers with any number of decimal places.

eldarerathis
+1  A: 

Use this regex for matching -

^\d+\.\d+$
Gopi
+1  A: 

per @mathew's answer you probably want to anchor your regex at the start and end of the string (so ^ and $ respectively). per @eldarerathis you probably want to limit the number of digits after the decimal point. You may also want to allow an optional $ sign in front; and you probably want to allow the user to drop the cent's component altogether. So:

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

Which is

^         start of string
\$?       optional dollar sign
\d+       at least 1 digit.
(\.\d\d)? optional decimal point followed by exactly two digits 
          (you could use \d{2} here as well)
$         end of string
Recurse