Advertisement

Pattern library / Validation

Credit Card Number Regex

Card numbers run 13 to 19 digits, optionally grouped with spaces or dashes, and every brand has its own prefix. The pattern here validates the shape in one line; the notes give the brand-specific alternations — and the pitfalls are non-negotiable reading: regex is not Luhn, and regex is not PCI compliance.

The pattern
^[-. ]*([0-9][-. ]*){12,18}[0-9][-. ]*$
Load this pattern into the tester →

How the pattern works

Test it: match & no-match examples

Every row is loaded straight into the tester — click Try to see the match live:

InputResultWhy
4111 1111 1111 1111Match16 digits, space-separated (Visa test number)Try →
5500-0000-0000-0004MatchMastercard shape with dashesTry →
378282246310005MatchAmex: 15 digits, no separatorsTry →
4111111111111112Matchshape passes — Luhn rejects it (checksum runs in code)Try →
1234 5678 9012No matchonly 12 digits — minimum is 13Try →
card 4111111111111111No matchletters are not part of a numberTry →

Where to use it

JavaScript (shape + length)

const SHAPE = /^[-. ]*([0-9][-. ]*){12,18}[0-9][-. ]*$/;
const digits = v.replace(/[^0-9]/g, '');
const ok = SHAPE.test(v) && digits.length >= 13 && digits.length <= 19;

Python (Luhn after shape)

def luhn(s):
    s = re.sub(r'\D', '', s)
    total = 0
    for i, ch in enumerate(s[::-1]):
        n = int(ch)
        if i % 2:
            n = n * 2 if n < 5 else n * 9
        total += n
    return total % 10 == 0

BigQuery (RE2)

WHERE REGEXP_CONTAINS(REPLACE(card, ' ', ''), r'^[0-9]{13,19}$')

Common mistakes

Test this pattern on your own data
Paste it into the free tester with your real strings — nothing leaves your browser.
Open the regex tester →

FAQ

Does this regex check the Luhn checksum?

No — regex checks shape only (13–19 digits, optional grouping). Implement the mod-10 Luhn algorithm in code; the Python snippet above is eight lines.

How do I match a specific card brand?

Use the brand patterns from the notes: Visa starts with 4, Mastercard with 51–55 (and 2221–2720), Amex with 34 or 37. Combine them with | if you accept several brands.

Is this pattern RE2-safe for BigQuery or GA4?

Yes — classes, quantifiers and groups only. But the stronger rule stands: card numbers do not belong in analytics at all; keep the pattern in forms and log checks.

IBAN Regex — Validate International Bank Account Numbers · Phone Number Regex — International & US Formats · Extract Numbers from String — Regex + Examples

For GA4-specific patterns, see the GA4 regex cheat sheet, the page path regex guide, the event filter regex guide, the GA4 regex match types, the custom channel grouping guide and RE2 vs PCRE. Browse the full regex pattern library.