Regular expression to match number with Decimal separator and optional Thousands separator

The reason the second alternative isn't matching is because it only allows a single \f after the decimal point. That needs to be \d+.

Then you need to wrap everything between ^ and $ in a group, so all alternatives match the entire string.

You had lots of redundant parentheses. And \d* in the last alternative should be \d+, otherwise you'll allow a number that's completely empty or just a sign.

^[+-]?([0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?|\d*\.\d+|\d+)$
  • ^ -> start of string
  • [+-]? -> matches optional + or - char
  • ([0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?|\d*\.\d+|\d+) -> whole group has to match [0-9]{1,3}(,[0-9]{3})*(\.[0-9]+) or \d*\.\d+ or \d+
    • [0-9]{1,3}(,[0-9]{3})*(\.[0-9]+) -> matches numbers with thousand separators and maybe decimal separator
    • \d*\.\d+ -> matches numbers with decimal separator, and maybe digits before the decimal
    • \d+ -> matches numbers without decimal separator
  • $ -> end of string

DEMO


You may use this regex for validation:

^[+-]?(?:\d+|\d{1,3}(?:,\d{3})*)(?:\.\d*)?$

RegEx Demo

It matches following cases:

Tags:

Regex