Python (re)

US Phone Number in PY

Match US phone numbers in common formats: (555) 867-5309, 555-867-5309, 5558675309.

Try it in the PY tester →

Pattern

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

Python (re) code

pyPython
import re

pattern = re.compile(r"\(?\d{3}\)?[\s.\-]?\d{3}[\s.\-]?\d{4}")
input_text = "(555) 867-5309"
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

The optional \(? and \)? allow parentheses around the area code. The [\s.\-]? between groups allows spaces, dots, or hyphens as optional separators.

Examples

Input

(555) 867-5309

Matches

  • (555) 867-5309

Input

555.867.5309

Matches

  • 555.867.5309

Input

5558675309

Matches

  • 5558675309

Same pattern, other engines

← Back to US Phone Number overview (all engines)