What Regex Matches Digits Only?
Match digits only: ^\d+$ or ^[0-9]+$. The ^ anchors to the start of the string, \d (or [0-9]) matches a single digit, + means one or more, and $ anchors to the end. This ensures the entire string contains nothing but digits.
Variations
| Pattern | Meaning | Matches |
|---|---|---|
^\d+$ | One or more digits | "123", "0", "999" |
^\d*$ | Zero or more digits | "", "123", "0" |
^\d{4}$ | Exactly 4 digits | "2026", "0001" |
^\d{3,5}$ | 3 to 5 digits | "123", "12345" |
Usage Examples
JavaScript
/^\d+$/.test('12345'); // true
/^\d+$/.test('12.34'); // false
/^\d+$/.test('abc'); // false
/^\d+$/.test(''); // false
Python
import re
bool(re.match(r'^\d+$', '12345')) # True
bool(re.match(r'^\d+$', '12.34')) # False
# Alternative: str.isdigit()
'12345'.isdigit() # True
\d vs [0-9]
In Python and Java, \d matches any Unicode digit (Arabic-Indic, Devanagari, etc.), while [0-9] matches only ASCII digits. In JavaScript (without the u flag), \d is equivalent to [0-9]. For strict ASCII-only validation, always use [0-9].
Try It Yourself
Test this regex with our Regex Tester.