Python Practice › RegEx Programs › Program 14

Mask card numbers

EasyRegEx Programs · 14 of 20

Write a Python program to mask all but the last 4 digits of card numbers.

Advertisement
Output
Card XXXX-XXXX-XXXX-1234 and XXXX-XXXX-XXXX-9876

Approach

  1. Capture the last 4 digits and replace the rest.

Solution

Python
import re text = "Card 4111 1111 1111 1234 and 5500-0000-0000-9876"print(re.sub(r"\d{4}[ -]\d{4}[ -]\d{4}[ -](\d{4})", r"XXXX-XXXX-XXXX-\1", text))
Output
Card XXXX-XXXX-XXXX-1234 and XXXX-XXXX-XXXX-9876

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs

Leave a Comment