go 41 lines · 6 steps

Masking card numbers in Go

Two functions that strip non-digits and replace all but the last four digits with asterisks — one for a single value, one for free text.

Explained by highlit
1package payment
2 
3import (
4 "regexp"
5 "strings"
6)
7 
8var cardPattern = regexp.MustCompile(`\b(?:\d[ -]?){12,15}\d\b`)
9 
10func MaskCardNumber(card string) string {
11 var digits strings.Builder
12 for _, r := range card {
13 if r >= '0' && r <= '9' {
14 digits.WriteRune(r)
15 }
16 }
17 
18 clean := digits.String()
19 if len(clean) < 4 {
20 return card
21 }
22 
23 last4 := clean[len(clean)-4:]
24 return strings.Repeat("*", len(clean)-4) + last4
25}
26 
27func MaskCardsInText(text string) string {
28 return cardPattern.ReplaceAllStringFunc(text, func(match string) string {
29 var digits strings.Builder
30 for _, r := range match {
31 if r >= '0' && r <= '9' {
32 digits.WriteRune(r)
33 }
34 }
35 clean := digits.String()
36 if len(clean) < 13 {
37 return match
38 }
39 return strings.Repeat("*", len(clean)-4) + clean[len(clean)-4:]
40 })
41}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Normalizing input by extracting only digits lets masking logic ignore spaces and dashes entirely.
  2. 2ReplaceAllStringFunc lets you run custom per-match logic instead of a fixed replacement string.
  3. 3Guard clauses that return the original input keep short or non-card values untouched.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Masking card numbers in Go — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code