RRegexBuilder
Get RegexBuilder

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.

InputResultMatched
0matches0
42matches42
007matches007
(empty string)no match
4 2no match
42ano match
-42no match
4.2no 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 RegexBuilder

Other regex answers