tags:

views:

79

answers:

4
+1  Q: 

RegEx for Prices?

Hi Chaps,

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?

+3  A: 
^\d+,\d{1,2}$
Matthew Scharley
yours is better.I'm trying to get optional decimals
Stefano Borini
+2  A: 

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.

Andrea Ambu
A: 

@Bart I got it totally wrong. I was trying to match prices like 10,256,543.45 (but failed).

OP wanted just 10256543,45

Amarghosh
Nope, that would match strings like: `,,,,,,,,,,,,,,,` and `0,0,0,0,0,0,0`
Bart Kiers
Oops, I was trying to match strings like 10,256,543.45 (but failed). regex is not my cup of tea.
Amarghosh
No problem. FYI, a regex for such numbers would be: `\d{1,3}(,\d{3})*\.\d{1,2}`
Bart Kiers
Thanks, I was struggling with that. Now I fully understand the meaning of "now you have two problems" joke on regex :)
Amarghosh
@Bart I tried to modify that regex, met with a roadblock and posted it as a question here http://stackoverflow.com/questions/1565994/
Amarghosh
A: 

anything like \d+,\d{2} is wrong because the \d matches [0-9\.] i.e. 12.34,1.

should be: [0-9]+,[0-9]{2} (or [0-9]+,[0-9]{1,2} to allow only 1 decimal place)

anon
No, \d does not match a '.', it is the same as [0-9]
Bart Kiers
Wrong. \d is short for [0-9] http://www.regular-expressions.info/charclass.html
Amarghosh