Regex for digits only
A regular expression that accepts a string of digits and nothing else, why it uses [0-9] rather than \d, and variants for signs, decimal points and thousands separators.
This tool runs in your browser. We never send what you type or paste to a server.
The pattern
/^[0-9]+$/Use this for codes that are made of digits, such as a one-time passcode, a sort code without hyphens or an account number. For quantities that can be negative or have a fractional part, use one of the variants further down.
The tester at the top of this page is loaded with this pattern and the examples below, one per line. It adds the m flag so that ^ and $ apply to each line, and g to show every match. Edit either box to try your own input.
How it works, token by token
| Part | Meaning |
|---|---|
^ | Start of the string. |
[0-9]+ | One or more of the characters 0 to 9. Change + to * to also allow an empty string, or to {6} for exactly six digits. |
$ | End of the string. |
What it matches and what it rejects
| Input | Result | Why |
|---|---|---|
0 | matches | One digit. |
42 | matches | Two. |
007 | matches | Leading zeros are kept: fine for codes, odd for amounts. |
12345678901234567890 | matches | Any length, including numbers too big for a 64-bit integer. |
(empty string) | rejected | Empty: + needs at least one digit. |
-5 | rejected | A sign. |
3.14 | rejected | A decimal point. |
1,000 | rejected | A thousands separator. |
1 000 | rejected | A space. |
٤٢ | rejected | Arabic-Indic digits four and two: rejected here, but \d accepts them in Python and .NET. |
42\n | rejected | A trailing line break: JavaScript's $ does not match before it. |
Why [0-9] and not \d
In JavaScript \d means exactly [0-9]. In Python 3 and .NET it means any character Unicode classes as a decimal digit, which includes the Arabic-Indic, Devanagari and many other digit sets:
console.log(/^\d+$/.test('\u0664\u0662'), /^[0-9]+$/.test('\u0664\u0662')); // → false false \d is ASCII only in JavaScriptprint(bool(re.fullmatch(r'\d+', '\u0664\u0662')), bool(re.fullmatch(r'\d+', '\u0664\u0662', re.ASCII))) # → True FalseConsole.WriteLine(System.Text.RegularExpressions.Regex.IsMatch("\u0664\u0662", @"^\d+$")); // → True \d matches any Unicode digit in .NET
Console.WriteLine(System.Text.RegularExpressions.Regex.IsMatch("\u0664\u0662", @"^\d+$", System.Text.RegularExpressions.RegexOptions.ECMAScript)); // → FalseThat matters when a pattern guards something that later treats the text as ASCII, such as a database column, a file name or another system. Python's int() converts those digits without complaint, so a value can pass your check and come out as a number you did not expect. Writing [0-9] means the same thing in every language. Python's re.ASCII flag and .NET's RegexOptions.ECMAScript also restrict \d to ASCII.
Signs, decimals and separators
A whole number with an optional sign:
/^[+-]?[0-9]+$/| Input | Result | Why |
|---|---|---|
42 | matches | No sign. |
-42 | matches | Negative. |
+42 | matches | Explicitly positive. |
--42 | rejected | Two signs. |
4-2 | rejected | A sign in the middle. |
- | rejected | A sign alone. |
A decimal number with an optional sign. The alternation allows a missing digit on one side of the point but not both:
/^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/| Input | Result | Why |
|---|---|---|
3.14 | matches | A decimal. |
-0.5 | matches | Negative. |
.5 | matches | No digit before the point. |
5. | matches | None after it. |
. | rejected | A point alone. |
1e5 | rejected | Exponents are not covered. |
1,5 | rejected | A decimal comma. |
1.2.3 | rejected | Two points. |
Digits grouped in threes with commas, as written in the UK and the US:
/^[0-9]{1,3}(?:,[0-9]{3})*$/| Input | Result | Why |
|---|---|---|
999 | matches | Under a thousand. |
1,000 | matches | One separator. |
1,234,567 | matches | Several. |
1,00 | rejected | Groups after a comma have three digits. |
10000 | rejected | Separators are required once there are more than three digits. |
,100 | rejected | A leading comma. |
Many countries write 1.000,5 where the UK writes 1,000.5, so a pattern for formatted numbers only works for one convention. If you accept numbers typed by people in several countries, parse them with a locale-aware library, or ask for plain digits.
Converting after the check
The pattern is worth running before converting because the usual conversion functions are lenient in different ways:
console.log(Number(''), Number(' 42 '), parseInt('42abc', 10)); // → 0 42 42print(int('\u0664\u0662'), int(' 42 ')) # → 42 42JavaScript's Number('') is 0, parseInt stops at the first non-digit and ignores the rest, and both Number and Python's int ignore surrounding spaces. Also check the size: 12345678901234567890 is all digits but larger than JavaScript can store exactly, so keep long identifiers as strings or use BigInt.
On a web form, <input inputmode="numeric" pattern="[0-9]*"> brings up a number pad on phones and checks the value; the browser anchors the pattern attribute to the whole value, so it needs no ^ or $. type="number" is meant for quantities and drops leading zeros, so avoid it for codes.
In JavaScript, Python, PHP and C#
JavaScript
const re = /^[0-9]+$/;
console.log(re.test('0')); // → true
console.log(re.test('-5')); // → false
Python
import re
pattern = re.compile(r'[0-9]+')
print(bool(pattern.fullmatch('0'))) # → True
print(bool(pattern.fullmatch('-5'))) # → False
PHP
<?php
$pattern = '/^[0-9]+$/D';
echo preg_match($pattern, '0'), "\n"; // → 1
echo preg_match($pattern, '-5'), "\n"; // → 0
C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^[0-9]+\z");
Console.WriteLine(pattern.IsMatch("0")); // → True
Console.WriteLine(pattern.IsMatch("-5")); // → FalseEach version checks the whole string. JavaScript's $ only matches at the very end, but Python, PHP and .NET also let $ match just before a final line break, so "abc\n" could slip through. The Python version uses re.fullmatch (so the ^ and $ are dropped), PHP adds the D modifier, and C# ends with \z.
The JavaScript, Python and C# examples are run before each update and their output is compared with the comments. PHP is not installed on our build machine, so the PHP version is checked against the PCRE pattern modifier documentation, and its string literal is checked to hand PHP exactly the pattern tested here.
Questions
What is the regex for numbers only?
^[0-9]+$ matches one or more digits and nothing else. Use ^[0-9]*$ to also allow an empty string.
Is \d the same as [0-9]?
In JavaScript, yes. In Python 3 and .NET, \d also matches digits from other scripts, such as Arabic-Indic digits, so [0-9] is the safer choice when you mean ASCII digits.
How do I allow exactly six digits, for a verification code?
Use ^[0-9]{6}$. For a range of lengths, such as 4 to 8 digits, use ^[0-9]{4,8}$.