Regex for digits only, integers and decimals
^\d+$ matches digits only. ^-?\d+$ adds an optional minus for integers. ^-?\d+(?:\.\d+)?$ also allows a fractional part, so 3.14 and -0.5 match but .5 and 5. do not.
JavaScript ✓PCRE ✓
No catastrophic-backtracking patterns found. (A heuristic check: nested and adjacent repeats, overlapping alternatives.)
^Start of the stringanchor-The character '-'literal?Repeat it optionally (zero or one time)quantifier\dA digit (0-9)character type+Repeat it one or more times, as many as possible (greedy)quantifier(?:…)Non-capturing group: groups without rememberinggroup\.The character '.' literallyliteral\dA digit (0-9)character type+Repeat it one or more times, as many as possible (greedy)quantifier?Then repeat the whole group optionally (zero or one time)quantifier$End of the stringanchor
Examples
Checked at build time in JavaScript and in Python's re.
| Input | Matches? |
|---|---|
42 | ✓ match |
-17 | ✓ match |
3.14 | ✓ match |
007 | ✓ match |
-0 | ✓ match |
.5 | ✗ no match |
5. | ✗ no match |
+5 | ✗ no match |
1,000 | ✗ no match |
1e3 | ✗ no match |
Try your own text
One string per line: each line is tested on its own (the m flag is added here).
How it works
The decimal pattern requires digits on both sides of the dot. That rejects 5. and .5, which most programming languages accept but which look like typos in a form. The fractional part is a single optional group, so the dot cannot appear without digits after it.
Avoid writing \d+\.?\d*. Without the dot, \d+ and \d* can split the same run of digits many ways, so a failing match is quadratic in the length of the number. Putting the dot and its digits in one group, as here, gives a single way to match.
Variants
/^\d+$/Digits only. No sign, no decimal point, at least one digit./^[+-]?\d+$/Integer with an optional plus or minus sign./^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/Any decimal literal, including.5,5.and exponents like1e-3.
Gotchas
- Leading zeros pass:
007matches. If the value is an ID or ZIP code, that is right. If it is a quantity, you may want^-?(?:0|[1-9]\d*). - In JavaScript
\dis ASCII 0-9 only, even with theuflag. In Python 3,\dalso matches other scripts' digits such as Arabic-Indic٣, unless you passre.ASCII. - Matching the format does not make it safe to convert.
Number("99999999999999999")silently loses precision past 2^53. UseBigIntor a string for long IDs. - Locales differ:
1.234,5is a normal way to write 1234.5 in Germany. UseIntl.NumberFormatto parse user-entered amounts.
Related explainers
- Regex for a US ZIP codeA regex for 5-digit US ZIP codes and ZIP+4, why ZIP codes must be stored as strings, and what a format...
- Regex for an IPv4 addressA strict IPv4 regex that only accepts octets 0-255 and rejects leading zeros, with the edge cases where...
- Regex for a semantic version (SemVer)A readable regex for semantic versions like 1.2.3-beta.1+build.5, how it differs from the official...