Regex for Money

39,537

Solution 1

\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.

Solution 2

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)

Solution 3

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

Solution 4

i used this one in javascript: may be of use for you in c#

var entered = '10.00';
var regex = /^\d+(?:\.\d{2})?$/; // starts with N digits optional ".\d\d"
console.log(entered.match(regex));
Share:
39,537
abatishchev
Author by

abatishchev

This is my GUID. There are many like it but this one is mine. My GUID is my best friend. It is my life. I must master it as I must master my life. Without me, my GUID is useless. Without my GUID I am useless.

Updated on November 20, 2020

Comments

  • abatishchev
    abatishchev over 3 years

    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'.

  • tanascius
    tanascius almost 15 years
    you don't have to escape the comma, do you?
  • Helen
    Helen almost 15 years
    It's better to use a non-capturing group since there's no need to capture the submatch.
  • balpha
    balpha almost 15 years
    Helen: True, I've added that.