Regex for Money

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

Leave a Comment