breakitdown

Regex for digits only, integers and decimals

Answer

^\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.

flags: g all matches · i ignore case · m ^ $ per line · s . matches newlines · u Unicode

JavaScript ✓PCRE ✓

No catastrophic-backtracking patterns found. (A heuristic check: nested and adjacent repeats, overlapping alternatives.)

  1. ^Start of the stringanchor
  2. -The character '-'literal
  3. ?Repeat it optionally (zero or one time)quantifier
  4. \dA digit (0-9)character type
  5. +Repeat it one or more times, as many as possible (greedy)quantifier
  6. (?:…)Non-capturing group: groups without rememberinggroup
  7. \.The character '.' literallyliteral
  8. \dA digit (0-9)character type
  9. +Repeat it one or more times, as many as possible (greedy)quantifier
  10. ?Then repeat the whole group optionally (zero or one time)quantifier
  11. $End of the stringanchor

Examples

Checked at build time in JavaScript and in Python's re.

InputMatches?
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

Gotchas

Related explainers

← Explain any regular expression