Python (re)

US ZIP Code in PY

Match US ZIP codes in 5-digit (12345) and ZIP+4 (12345-6789) formats.

Try it in the PY tester →

Pattern

regexPY
\b\d{5}(?:[\-\s]\d{4})?\b   (flags: g)

Python (re) code

pyPython
import re

pattern = re.compile(r"\b\d{5}(?:[\-\s]\d{4})?\b")
input_text = "90210"
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

Core is 5 digits. The optional group (?:[\-\s]\d{4})? adds support for the ZIP+4 extension separated by hyphen or space.

Examples

Input

90210

Matches

  • 90210

Input

10001-1234

Matches

  • 10001-1234

Input

1234

No match

Same pattern, other engines

← Back to US ZIP Code overview (all engines)