Python (re)

Credit Card Number in PY

Match 16-digit credit card numbers with optional spaces or hyphens between groups of 4.

Try it in the PY tester →

Pattern

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

Python (re) code

pyPython
import re

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

Three groups of 4 digits with optional space/hyphen separators, followed by a final 4-digit group. Word boundaries prevent partial matches.

Examples

Input

4111 1111 1111 1111

Matches

  • 4111 1111 1111 1111

Input

4111-1111-1111-1111

Matches

  • 4111-1111-1111-1111

Input

4111111111111111

Matches

  • 4111111111111111

Same pattern, other engines

← Back to Credit Card Number overview (all engines)