Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for Prices?

Tags:

regex

I am searching for a RegEx for prices. So it should be X numbers in front, than a "," and at the end 2 numbers max.

Can someone support me and post it please?

like image 658
PassionateDeveloper Avatar asked Oct 10 '09 10:10

PassionateDeveloper


People also ask

What is $/ in regex?

The /^$/ component is a regular expression that matches the empty string. More specifically, it looks for the beginning of a line ( ^ ) followed directly by the end of a line ( $ ), which is to say an empty line.

What does $1 do in regex?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

Is regular expression expensive?

Yes, regex is expensive, so use it wisely.

What is IOS regex?

A regex ( also known as regular expressions) is a pattern string. These pattern strings allow you to search specific patterns in documents and to validate email, phone number etc. In iOS and MacOS regex been handled by NSRegularExpression . To know more about NSRegularExpression read apple documentation.


2 Answers

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.

like image 69
Andrea Ambu Avatar answered Sep 28 '22 06:09

Andrea Ambu


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})?
like image 31
elgehelge Avatar answered Sep 28 '22 05:09

elgehelge