The Pattern
``regex
^\$?(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d{2})?$
`
Flags: gm ā multiline, so ^ and $ anchor to each line rather than the whole input.
What It Accepts and Rejects
| Input | Result |
|---|---|
$1,299.00 | ā matches |
1299 | ā matches |
$0.99 | ā matches |
1,29.00 | ā rejected |
$1,2999 | ā rejected |
Thousands Groups Must Be Exactly Three
The alternation \d{1,3}(?:,\d{3})*|\d+ gives two mutually exclusive shapes: a grouped
number where every group after the first is exactly three digits, or an ungrouped run of
digits with no commas at all.
That is what rejects 1,29.00 (a two-digit group) and $1,2999 (a four-digit group)
while accepting both 1,299.00 and 1299.
The decimal part is (?:\.\d{2})? ā optional, and exactly two digits when present, which
matches how currency is written rather than how numbers are.
The Limits of This Pattern
This pattern is US-centric in a way that matters. Most of Europe writes 1.299,00 with
the separators reversed, Switzerland uses apostrophes, and India groups as 12,34,567. It
also assumes two decimal places, which is wrong for JPY (zero) and KWD (three).
More fundamentally: never store money as a formatted string or a float. Parse to integer
minor units ā cents ā as early as possible and format only for display.
Testing Before Shipping
A regex that has only been tried against inputs you expect to match is untested. Every
pattern needs three kinds of case:
1. Valid inputs that should match, including the awkward-but-legal ones.
2. Invalid inputs that should not, especially near-misses that differ by one character.
3. Adversarial inputs ā very long strings, unusual Unicode, and nesting that could
trigger catastrophic backtracking.
Paste your own examples into the tester above and watch which lines highlight. A pattern
that matches everything you throw at it is usually too permissive rather than correct.
Catastrophic Backtracking
Nested quantifiers over overlapping character classes ā (a+)+, (\w+\s?)* ā can take
exponential time on a non-matching input. On a server that is a denial-of-service bug, not a
performance issue. If a pattern is applied to user input, bound the input length first and
prefer explicit alternation over nested repetition.
Anchors, Greediness and Backtracking
Three behaviours account for most regex surprises, and this pattern shows all three.
Anchors. ^ and $ pin the match to the start and end of the input. Without them,
\d{3} matches the 123 inside abc123def. With m in the flags ā as here ā they
pin to each *line* instead, which is what lets one pattern be tested against a list.
Greediness. .* takes as much as it can and gives back only when forced; .*? takes
as little as possible. On , the pattern <.*> matches the whole string and
<.*?> matches just .
Testing It Properly
`javascript
const pattern = /^\$?(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d{2})?$/gm;