tags:

views:

511

answers:

3
+1  Q: 

Regex for Money

I have asp:TextBox to keep a value of money, i.e. '1000', '1000,0' and '1000,00' (comma is the delimiter because of Russian standard).

What ValidationExpression have I to use into appropriate asp:RegularExpressionValidator?

I tried \d+\,\d{0,2} but it doesn't allows a number without decimal digits, e.g. just '1000'.

+9  A: 
\d+(,\d{1,2})?

will allow the comma only when you have decimal digits, and allow no comma at all. The question mark means the same as {0,1}, so after the \d+ you have either zero instances (i.e. nothing) or one instance of

,\d{1,2}

As Helen points out correctly, it will suffice to use a non-capturing group, as in

\d+(?:,\d{1,2})?

The additional ?: means that the parentheses are only meant to group the ,\d{1,2} part for use by the question mark, but that there is no need to remember what was matched within these parenthesis. Since this means less work for the regex enginge, you get a performance boost.

balpha
you don't have to escape the comma, do you?
tanascius
you're right, correcting it
balpha
It's better to use a non-capturing group since there's no need to capture the submatch.
Helen
Helen: True, I've added that.
balpha
Thanks a lot for advanced explanation!
abatishchev
+1  A: 

http://regexlib.com/Search.aspx?k=money

Hardwareguy
A: 

We use this very liberal regular expression for money validation:

new Regex(@"^\-?\(?\$?\s*\-?\s*\(?(((\d{1,3}((\,\d{3})*|\d*))?(\.\d{1,4})?)|((\d{1,3}((\,\d{3})*|\d*))(\.\d{0,4})?))\)?$");

It allows all these: $0, 0, (0.0000), .1, .01, .0001, $.1, $.01, $.0001, ($.1), ($.01), $(.0001), 0.1, 0.01, 0.0001, 1., 1111., 1,111., 1, 1.00, 1,000.00, $1, $1.00, $1,000.00, $ 1.0000, $ 1.0000, $ 1,000.0000, -1, -1.00, -1,000.00, -$1, -$1.00, -$1,000.00, -$ 1, -$ 1.00, -$ 1,000.00, $-1, $-1.00, $-1,000.00, $(1), $(1.00), $(1,000.00), $ (1), $ (1.00), $ (1,000.00), ($1), ($1.00), ($1,000.00)

Jade Ohlhauser