Mask Card Numbers in Text

Medium ⏱ 12 min 50% acceptance ★★★★☆ 4.3
Write mask_cards(text) replacing every 16-digit run (optionally grouped as 4×4 with spaces or hyphens) so only the last four digits survive: '** ** 1234'. Use re.sub with a function or backreference for the kept group.

Examples

Example 1
Input
mask_cards('pay with 4242 4242 4242 4242 today')
Output
'pay with **** **** **** 4242 today'
Explanation

Twelve digits masked, last four kept.

Constraints

  • Handle plain, space- and hyphen-grouped forms.
  • Keep the final 4 digits.

Topics

Regular Expressionssub

Companies

StripePayPalRazorpay

Hints

Hint 1

Pattern: \b(?:\d{4}[ -]?){3}(\d{4})\b.

Hint 2

Replacement: '**** **** **** \\1' or a lambda using m.group(1).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.