Regex patterns/Numbers

Currency amount

Thousands separators in groups of three, with exactly two decimal places.

/^\$?\d{1,3}(?:,\d{3})*(?:\.\d{2})?$/
Open it in Rex

The problem

Check that a string is a formatted money amount with thousands separators.

How it reads

start\$skip\drepeatgroup,\drepeatrepeatskipgroup\.\drepeatskipend

Follow the line from left to right — every path you can trace is a string this pattern matches.

  1. ^\$?\d{1,3}(?:,\d{3})…In order:
  2. ^The start of the text (or of a line with the m flag)
  3. \$?The character "$", optionally (zero or one time)
  4. \d{1,3}A digit, between 1 and 3 times, as many as possible
  5. (?:,\d{3})*Repeated any number of times, including none, as many as possible:
  6. (?:,\d{3})Group (not captured):
  7. ,\d{3}In order:
  8. ,The character ","
  9. \d{3}A digit, exactly 3 times, as many as possible
  10. (?:\.\d{2})?Repeated optionally (zero or one time):
  11. (?:\.\d{2})Group (not captured):
  12. \.\d{2}In order:
  13. \.The character "."
  14. \d{2}A digit, exactly 2 times, as many as possible
  15. $The end of the text (or of a line with the m flag)

Matches

  • $1,234.56
  • 999
  • $0.99
  • 12,345,678.00

Does not match

  • $12,34.5
  • 1234.5
  • $1,2345.00
  • free

Where it bites

  • The first group is {1,3} and every later one is exactly {3} — that is what rejects "1,2345".
  • Exactly two decimal places are required when there is a decimal point at all; "1.5" fails. Use {1,2} if that is too strict.
  • Only the dollar sign is allowed, and formatting differs by locale. Intl.NumberFormat is the reliable way to produce these; this validates one convention.

More numbers patterns