Python (re)

JSON Number (Strict) in PY

Match JSON-spec numbers — disallows leading zeros (no `01`), allows decimals and exponents.

Try it in the PY tester →

Pattern

regexPY
-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][-+]?\d+)?   (flags: g)

Python (re) code

pyPython
import re

pattern = re.compile(r"-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][-+]?\d+)?")
input_text = "values: 0, 42, -3.14, 6.022e23"
for m in pattern.finditer(input_text):
    print(m.group(0))

Stdlib `re` module — no third-party dependency. Works on Python 3.6+.

How the pattern works

-? optional sign. (?:0|[1-9]\d*) the integer part: either a single zero or a non-zero digit followed by any digits (no leading zeros allowed per RFC 8259). (?:\.\d+)? optional decimal part. (?:[eE][-+]?\d+)? optional exponent. Strict per JSON spec — won't match `01` or `1.` (which are valid JS but not JSON).

Examples

Input

values: 0, 42, -3.14, 6.022e23

Matches

  • 0
  • 42
  • -3.14
  • 6.022e23

Input

0.5 vs invalid 01

Matches

  • 0.5
  • 0
  • 1

Input

no numbers

No match

Same pattern, other engines

← Back to JSON Number (Strict) overview (all engines)