RegEx for Prices?

In what language are you going to use it?

It should be something like:

^\d+(,\d{1,2})?$

Explaination:

X number in front is: ^\d+ where ^ means the start of the string, \d means a digit and + means one or more

We use group () with a question mark, a ? means: match what is inside the group one or no times.

inside the group there is ,\d{1,2}, the , is the comma you wrote, \d is still a digit {1,2} means match the previous digit one or two times.

The final $ matches the end of the string.


I was not satisfied with the previous answers. Here is my take on it:

\d{1,3}(?:[.,]\d{3})*(?:[.,]\d{2})

|^^^^^^|^^^^^^^^^^^^^|^^^^^^^^^^^|
| 1-3  | 3 digits    | 2 digits  |
|digits| repeat any  |           |
|      | no. of      |           |
|      | times       |           |

(get a detailed explanation here: https://regex101.com/r/cG6iO8/1)

Covers all cases below

  • 5.00
  • 1,000
  • 1,000,000.99
  • 5,99 (european price)
  • 5.999,99 (european price)
  • 0.11
  • 0.00

But also weird stuff like

  • 5.000,000.00

In case you want to include 5 and 1000 (I personally wound not like to match ALL numbers), then just add a "?" like so:

\d{1,3}(?:[.,]\d{3})*(?:[.,]\d{2})?

I am working on similar problem. However i want only to match if a currency Symbol or String is also included in the String like EUR,€,USD or $. The Symbol may be trailing or leading. I don't care if there is space between the Number and the Currency substring. I based the Number matching on the previous discussion and used Price Number: \d{1,3}(?:[.,]\d{3})*(?:[.,]\d{2})?

Here is final result:

(USD|EUR|€|\$)\s?(\d{1,3}(?:[.,]\d{3})*(?:[.,]\d{2}))|(\d{1,3}(?:[.,]\d{3})*(?:[.,]\d{2})?)\s?(USD|EUR|€|\$)

I use (\d{1,3}(?:[.,]\d{3})*(?:[.,]\d{2})?)\s?(USD|EUR|€|\$) as a pattern to match against a currency symbol (here with tolerance for a leading space). I think you can easily tweak it for any other currencies

A Gist with the latest Version can be found at https://gist.github.com/wischweh/b6c0ac878913cca8b1ba

Tags:

Regex