Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 504
abatishchev Avatar asked Jun 22 '09 16:06

abatishchev


People also ask

Is regex matching expensive?

Avoid coding in regex if you can Don't solve important problems with regex. regex is expensive – regex is often the most CPU-intensive part of a program. And a non-matching regex can be even more expensive to check than a matching one.

What is the regex for numbers?

To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

What is question mark in regex?

A regular expression followed by a question mark (?) matches zero or one occurrences of the regular expression. Two regular expressions concatenated match an occurrence of the first followed by an occurrence of the second.

How do you match a space in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.


1 Answers

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

like image 103
balpha Avatar answered Oct 14 '22 15:10

balpha