How-to
How to Match Digits in Regex
Use \d for any digit, [0-9] for ASCII digits only, or {n} to match a specific count of digits. Combine with anchors for whole-string validation.
The shorthand
\d matches any digit. In JavaScript without the u flag it means [0-9]. With the u flag it also matches Unicode digits from other scripts (Arabic, Devanagari, etc.) — important to know if you're validating user input internationally.
Exact count
Combine \d with {n} to match exactly n digits — e.g. \d{4} for a 4-digit year. Use {n,m} for a range like \d{3,5} or {n,} for 'at least n.'
Digits only (reject other chars)
Wrap in ^...$ anchors: ^\d+$ only matches if the ENTIRE string is digits. Without anchors, \d+ would match the digits inside 'order 42' as a substring.
ASCII-only digits
If you specifically want 0-9 and nothing else (even under the u flag), use [0-9] instead of \d. Some form validators have been bitten by accepting Arabic-Indic or other Unicode digits that pass \d but aren't what a downstream database expects.
Related patterns
US Phone Number
Match US phone numbers in common formats: (555) 867-5309, 555-867-5309, 5558675309.
/\(?\d{3}\)?[\s.\-]?\d{3}[\s.\-]?\d…/gUS ZIP Code
Match US ZIP codes in 5-digit (12345) and ZIP+4 (12345-6789) formats.
/\b\d{5}(?:[\-\s]\d{4})?\b/gCredit Card Number
Match 16-digit credit card numbers with optional spaces or hyphens between groups of 4.
/\b(?:\d{4}[\s\-]?){3}\d{4}\b/gInteger
Matches whole integers, including negative numbers.
/^-?\d+$/