Regex for credit card numbers

A regular expression for the shape of a card number as people type it, patterns for the main card brands, and the Luhn check that a regex cannot do.

//

Matches

This tool runs in your browser. We never send what you type or paste to a server.

The pattern

/^(?:[0-9][ -]?){11,18}[0-9]$/

This pattern checks what a user can get wrong while typing: letters, a missing or extra digit, stray separators. It accepts 12 to 19 digits, which covers the card lengths in use (most are 15 or 16, some 19), grouped however the card prints them. Remove the spaces and hyphens before you do anything else with the number.

The tester at the top of this page is loaded with this pattern and the examples below, one per line. It adds the m flag so that ^ and $ apply to each line, and g to show every match. Edit either box to try your own input.

How it works, token by token

PartMeaning
^Start of the string.
(?:[0-9][␣-]?){11,18}Between 11 and 18 digits, each optionally followed by one space or hyphen.
[0-9]One final digit, so the number cannot end with a separator. In all, 12 to 19 digits.
$End of the string.

␣ stands for a space character.

What it matches and what it rejects

InputResultWhy
4242424242424242matchesSixteen digits: Stripe's Visa test number.
4242 4242 4242 4242matchesGrouped with spaces.
4242-4242-4242-4242matchesOr hyphens.
3782 822463 10005matchesAmerican Express groups 4-6-5.
6205500000000000004matchesNineteen digits.
4242424242424241matchesAccepted: the format is right, but the Luhn check fails.
4242 4242 4242 4242rejectedTwo spaces in a row.
4242 4242 4242 4242␣rejectedA trailing space: trim first.
42424242424rejectedEleven digits.
42424242424242424242rejectedTwenty.
4242-4242-4242-424XrejectedA letter.

Why the Luhn check is not in the regex

The last digit of a card number is a check digit computed with the Luhn algorithm: double every second digit from the right, subtract 9 from any result over 9, add everything up, and the total must be a multiple of 10. It catches any single mistyped digit and most swaps of two neighbouring digits. A regex matches characters, it cannot do arithmetic, so the check needs a few lines of code:

function luhn(number) {
  const digits = number.replace(/[ -]/g, '');
  if (!/^[0-9]{12,19}$/.test(digits)) return false;
  let sum = 0;
  for (let i = 0; i < digits.length; i++) {
    let d = Number(digits[digits.length - 1 - i]); // count from the right
    if (i % 2 === 1) {
      d *= 2;
      if (d > 9) d -= 9;
    }
    sum += d;
  }
  return sum % 10 === 0;
}

console.log(luhn('4242 4242 4242 4242'), luhn('4242 4242 4242 4241'));  // → true false
console.log(luhn('378282246310005'), luhn('6205500000000000004'));      // → true true
import re

def luhn(number):
    digits = re.sub(r'[ -]', '', number)
    if not re.fullmatch(r'[0-9]{12,19}', digits):
        return False
    total = 0
    for i, ch in enumerate(reversed(digits)):  # count from the right
        d = int(ch)
        if i % 2 == 1:
            d = d * 2 - 9 if d > 4 else d * 2
        total += d
    return total % 10 == 0

print(luhn('4242 4242 4242 4242'), luhn('4242 4242 4242 4241'))  # → True False
print(luhn('378282246310005'), luhn('6205500000000000004'))      # → True True

Passing the Luhn check only means the number was not mistyped. It says nothing about whether the card exists, has funds or belongs to the person typing it; only the payment provider can tell you that.

Telling the brands apart

The first digits identify the card network. Visa numbers start with 4:

/^4[0-9]{11,18}$/
InputResultWhy
4242424242424242matchesStripe's Visa test card.
5555555555554444rejectedMastercard.

Mastercard numbers are 16 digits starting with 51 to 55 or, since the 2-series was added, 2221 to 2720 (see Mastercard's BIN lookup documentation). Expressing a numeric range in regex means spelling it out digit by digit:

/^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$/
InputResultWhy
5555555555554444matchesA 51-55 number.
2223003122003222matchesA 2-series number.
2221000000000000matchesThe bottom of the 2-series range.
2720999999999999matchesThe top.
2220999999999999rejectedJust below the range.
2721000000000000rejectedJust above.
4242424242424242rejectedVisa.

American Express numbers are 15 digits starting with 34 or 37:

/^3[47][0-9]{13}$/
InputResultWhy
378282246310005matchesStripe's Amex test card.
371449635398431matchesAnother.
37828224631000rejectedFourteen digits.
4242424242424242rejectedVisa.

Use brand detection to show the right logo or the right grouping while someone types, not to reject cards. Networks add ranges, and an out-of-date pattern turns away real customers; the Mastercard 2-series is the classic example of a range that older patterns do not know. The examples use the published test numbers from Stripe's testing documentation.

Handling card numbers safely

Card numbers are covered by the PCI DSS security standard, and the simplest way to reduce your obligations is to never receive them: payment providers offer hosted card fields or checkout pages, so the number goes straight from the browser to the provider and your server only sees a token. If you do handle numbers, never write them to logs, analytics or error reports, and mask them when you show them (only the last four digits).

For the form field, use <input autocomplete="cc-number" inputmode="numeric"> so browsers can fill it from a saved card and phones show a number pad. Do not use type="number", which is for quantities and can mangle long numbers.

In JavaScript, Python, PHP and C#

JavaScript

const re = /^(?:[0-9][ -]?){11,18}[0-9]$/;
console.log(re.test('4242424242424242')); // → true
console.log(re.test('4242  4242 4242 4242')); // → false

Python

import re

pattern = re.compile(r'(?:[0-9][ -]?){11,18}[0-9]')
print(bool(pattern.fullmatch('4242424242424242')))  # → True
print(bool(pattern.fullmatch('4242  4242 4242 4242')))  # → False

PHP

<?php
$pattern = '/^(?:[0-9][ -]?){11,18}[0-9]$/D';
echo preg_match($pattern, '4242424242424242'), "\n"; // → 1
echo preg_match($pattern, '4242  4242 4242 4242'), "\n"; // → 0

C#

using System;
using System.Text.RegularExpressions;

var pattern = new Regex(@"^(?:[0-9][ -]?){11,18}[0-9]\z");
Console.WriteLine(pattern.IsMatch("4242424242424242")); // → True
Console.WriteLine(pattern.IsMatch("4242  4242 4242 4242")); // → False

Each version checks the whole string. JavaScript's $ only matches at the very end, but Python, PHP and .NET also let $ match just before a final line break, so "abc\n" could slip through. The Python version uses re.fullmatch (so the ^ and $ are dropped), PHP adds the D modifier, and C# ends with \z.

The JavaScript, Python and C# examples are run before each update and their output is compared with the comments. PHP is not installed on our build machine, so the PHP version is checked against the PCRE pattern modifier documentation, and its string literal is checked to hand PHP exactly the pattern tested here.

Questions

Can a regex validate a credit card number?

Only its format. A regex can check the length and the brand prefix, but not the Luhn check digit, which needs arithmetic, and not whether the card is real, which only the payment provider knows.

How many digits does a credit card number have?

Most cards have 15 digits (American Express) or 16 (Visa and Mastercard), and some have up to 19. The pattern on this page accepts 12 to 19 so that no real card is turned away.

What is the regex for a Visa card number?

Visa numbers start with 4, so ^4[0-9]{11,18}$ after removing spaces. Use it to pick the logo, not to reject cards.