Regex for credit card number

Use /^(?:4\d{12}(?:\d{3})?|5[1-5]\d{14}|3[47]\d{13})$/ to check that a whole string is a valid for credit card number. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^(?:4\d{12}(?:\d{3})?|5[1-5]\d{14}|3[47]\d{13})$/
Open in Regex Tester
InputResult
4111111111111111✓ Match
5500000000000004✓ Match
378282246310005✓ Match
1234567812345678✗ No match
4111 1111 1111 1111✗ No match
411111111111111✗ No match

How the pattern works

PartMeaning
4\d{12}(?:\d{3})?Visa: starts with 4, 13 or 16 digits
5[1-5]\d{14}Mastercard: 51–55, 16 digits
3[47]\d{13}American Express: 34 or 37, 15 digits

Code examples

JavaScript

const re = /^(?:4\d{12}(?:\d{3})?|5[1-5]\d{14}|3[47]\d{13})$/;
re.test(value); // true or false

Python

import re

bool(re.fullmatch(r'(?:4\d{12}(?:\d{3})?|5[1-5]\d{14}|3[47]\d{13})', value))

PHP

preg_match('/^(?:4\d{12}(?:\d{3})?|5[1-5]\d{14}|3[47]\d{13})$/', $value) === 1;

Notes and limitations

Remove spaces and dashes before testing, then run a Luhn checksum — the regex only checks the shape. Mastercard also issues 2221–2720 numbers; add |2(?:2[2-9]|[3-6]\d|7[01]|720)\d{12} to cover them. Never log or store raw card numbers. The examples are standard test numbers.

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex for credit card number?
/^(?:4\d{12}(?:\d{3})?|5[1-5]\d{14}|3[47]\d{13})$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: 4111111111111111, 5500000000000004, 378282246310005. The others don’t.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.