RegexBuilder · regex answers
Regex to match digits only
/^\d+$/
Anchored at both ends, this accepts a string made entirely of digits — with one caveat per language, spelled out below. Two traps live here. First, \d is not the same everywhere: in JavaScript it is always ASCII 0-9, but in Python a str pattern matches every Unicode decimal digit, so ٤٢ and ४२ both pass — use re.ASCII or [0-9] when you mean ASCII. Second, Python's $ also matches just before a trailing newline, so "42\n" satisfies ^\d+$ there; write \Z instead of $ to forbid it. JavaScript's $ without the m flag has no such hole.
What each part does
| ^ | start of string |
| \d+ | one or more digits |
| $ | end of string |
Tested against real input
Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.
| Input | Result | Matched |
|---|---|---|
| 0 | matches | 0 |
| 42 | matches | 42 |
| 007 | matches | 007 |
| (empty string) | no match | — |
| 4 2 | no match | — |
| 42a | no match | — |
| -42 | no match | — |
| 4.2 | no match | — |
The mistake to avoid
Leaving out the anchors. \d+ alone finds digits inside abc123 and reports a match, which is why 'my form accepts letters' bugs survive review.
Try it on your own text
Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.
Open RegexBuilderOther regex answers
- Regex for an email address
- Regex for a US phone number
- Regex for an IPv4 address
- Regex for a URL
- Regex for a date in YYYY-MM-DD format
- Regex for alphanumeric characters
- Regex to find special characters
- Regex for a strong password
- Regex to match whitespace
- Regex to trim leading and trailing whitespace
- Regex for a UUID
- Regex for a hex colour code