views:

955

answers:

3

Hi All

I am trying to find a piece of regex to match a currency value.

I would like to match only numbers and 1 decimal point ie

Allowed

  • 10
  • 100
  • 100.00

Not Allowed

  • Alpha Characters
  • 100,00
  • +/- 100

I have search and tried quite a few without any luck.

Hope you can advise

A: 

Try this regular expression:

^(?:[1-9]\d+|\d)(?:\.\d\d)?$
Gumbo
I tried this.return (preg_match('^(?:[1-9]\d+|\d)(?:\.\d\d)?$', $vale)) ? TRUE : FALSE;And just get error Message: preg_match() [function.preg-match]: No ending delimiter '^' found. Adding it everything passes.
Lee
preg_match('/^(?:[1-9]\d+|\d)(?:\.\d\d)?$/')
chaos
The `preg_*` functions use PCRE that need to be surrounded by delimiters. See http://docs.php.net/manual/en/intro.pcre.php
Gumbo
Still allowing invalid characters.return (preg_match('/^(?:[1-9]\d+|\d)(?:\.\d\d)?$/', $this->price) )? TRUE : FALSE;allows any Alpha character
Lee
@Lee: you should test the expression in a simple script (unit test for example): it should work as expected. I don't see how it would allow alpha chars.Actually, it doesn't (I just tested it).
PhiLho
Is there an error in my answer or why did it get down voted?
Gumbo
+1  A: 

You might want to consider other alternatives to using a regex.

For example, there's the NumberFormatter class, which provides flexible number and currency parsing and formatting, with build in internationalisation support.

It's built into PHP 5.3 and later, and is available as an extension on earlier versions of PHP 5.

therefromhere
A: 
if (preg_match('/^[0-9]+(?:\.[0-9]+)?$/im', $subject))
{
    # Successful match
}
else
{
    # Match attempt failed
}

Side note : If you want to restrict how many decimal places you want, you can do something like this :

/^[0-9]+(?:\.[0-9]{1,3})?$/im

So

100.000

will match, whereas

100.0001

wont.

If you need any further help, post a comment.

PS If you can, use the number formatter posted above. Native functions are always better (and faster), otherwise this solution will serve you well.

The Pixel Developer
But `123.` would match.
Gumbo
Thanks for bringing this to my attention. Fixed.
The Pixel Developer
Any reason for the down voting? If you see a genuine problem I'd be happy to tweak the answer. However, down voting without saying anything is just being silly especially when it's the accepted answer.
The Pixel Developer
This would still match `00000`, `0.1` and `0.123`. And besides the leading zeros, I don’t think Lee wanted a variable number of digits after the decimal point.
Gumbo