Visual regex workbench

Build, test, explain and master regex with visual tools, guides, examples and a growing regex library.

Regex guide

Credit Card Regex Examples

Credit card validation is a common use case for forms, checkout pages and payment interfaces. This guide provides practical regex examples for card number formats, explains brand-specific patterns, and shows why regex validation must be combined with checksum and payment-provider validation.

Generic Credit Card Number

Matches a generic 16-digit credit card number with optional spaces or hyphens between groups.

Suggested pattern

^(?:\d{4}[- ]?){3}\d{4}$
Quick test

Visa Card

Matches Visa card numbers. Visa cards always start with 4 and contain 13 or 16 digits.

Suggested pattern

^4\d{12}(?:\d{3})?$
Quick test

Mastercard

Matches Mastercard numbers, including both the traditional 51–55 range and the newer 2221–2720 range.

Suggested pattern

^(?:5[1-5]\d{14}|2(?:2[2-9]|[3-6]\d|7[01]|720)\d{12})$
Quick test

American Express

Matches American Express card numbers, which begin with 34 or 37 and contain 15 digits.

Suggested pattern

^3[47]\d{13}$
Quick test

Credit Card with Spaces or Hyphens

Matches credit card numbers formatted with either spaces or hyphens between each group of four digits.

Suggested pattern

^\d{4}(?:[- ]\d{4}){3}$
Quick test

Discover Card

Matches common Discover card numbers starting with 6011, 65 or 644–649.

Suggested pattern

^(?:6011\d{12}|65\d{14}|64[4-9]\d{13})$
Quick test

JCB Card

Matches JCB card numbers, including the historical 2131 and 1800 prefixes.

Suggested pattern

^(?:2131|1800|35\d{3})\d{11}$
Quick test

Diners Club

Matches Diners Club card numbers starting with 300–305, 36 or 38.

Suggested pattern

^3(?:0[0-5]|[68]\d)\d{11}$
Quick test

Last 4 Digits

Matches the last four digits of a credit card number, often displayed for security purposes.

Suggested pattern

\d{4}$
Quick test

Extract Credit Card Numbers

Extracts 16-digit credit card numbers from text, allowing optional spaces or hyphens.

Suggested pattern

\b(?:\d{4}[- ]?){3}\d{4}\b
Quick test

Accept Multiple Credit Card Formats

Accepts both compact 16-digit card numbers and numbers grouped with spaces or hyphens.

Suggested pattern

^(?:\d{16}|(?:\d{4}[- ]?){3}\d{4})$
Quick test

Mask Credit Card Numbers

Matches the middle digits of a credit card number so they can be replaced with masking characters.

Suggested pattern

(?<=\d{4})\d(?=\d{4})
Quick test

Payment Form Validation

Accepts most common credit card formats entered by users while typing into a payment form.

Suggested pattern

^\d(?:[ -]?\d){12,18}$
Quick test

Strict 16-Digit Card Number

Matches only a continuous 16-digit card number without spaces or separators.

Suggested pattern

^\d{16}$
Quick test

Find Card Numbers in Logs

Searches log files or text documents for potential credit card numbers that should be masked or removed.

Suggested pattern

\b(?:\d{4}[ -]?){3}\d{4}\b
Quick test

Can Regex Validate a Credit Card?

A regular expression can only verify that a credit card number follows the expected format. It cannot determine whether the card actually exists, whether it has expired or whether it is still valid.

Even a perfectly formatted number may be invalid. Real-world validation should always combine a regex with the Luhn checksum algorithm and server-side verification performed by your payment provider.

Use regex as the first validation step to improve the user experience, but never as the only validation mechanism.

Understanding Credit Card Number Structure

Most credit card numbers contain between 13 and 19 digits depending on the card issuer. The first digits identify the card network, while the remaining digits identify the customer account.

The final digit is a checksum calculated using the Luhn algorithm. This checksum helps detect typing mistakes but is not intended as a security feature.

Understanding this structure helps you choose the appropriate regex for each card type instead of relying on a single generic pattern.

Visa vs Mastercard Regex

Visa cards always begin with the digit 4, while Mastercard uses the historical 51–55 range as well as the newer 2221–2720 range.

Many outdated regex examples found online still ignore the newer Mastercard prefixes, leading to false validation failures.

Whenever possible, verify your patterns against the latest issuer specifications rather than copying old examples.

Supporting Spaces and Hyphens

Users rarely type long card numbers without separators. Most payment forms accept spaces or hyphens because they improve readability.

A flexible regex can accept these separators while still enforcing the expected number of digits.

Another common approach is to remove separators before validation, making both the regex and the subsequent processing simpler.

Extracting Credit Card Numbers from Text

Regular expressions are frequently used to locate potential credit card numbers inside logs, emails or imported documents.

After extraction, sensitive values should be masked, encrypted or removed before logs are stored or shared.

Be careful not to create patterns that are too permissive, as they may accidentally match unrelated numeric identifiers.

Masking Sensitive Card Numbers

Displaying only the last four digits of a credit card number is a common security practice used by banks and payment providers.

Regex lookarounds make it easy to replace only the middle digits while preserving the first and last digits for identification.

Masking protects sensitive information without preventing users from recognizing the card used for a transaction.

Common Regex Mistakes

One common mistake is forgetting anchors. Without ^ and $, a regex may match only part of the input instead of validating the whole value.

Another mistake is making separators too permissive, which can accidentally allow malformed values such as mixed spaces and hyphens.

For validation patterns, always decide whether you want to match the entire input or simply find a value inside a larger text.

Cross-Engine Compatibility

Most credit card regex patterns work in JavaScript, PCRE, Python, Java and many other engines because they mainly use basic syntax.

However, advanced examples using lookbehind or named groups may behave differently depending on the regex engine.

When a pattern will be used in production, always test it in the same engine and language that your application uses.

Performance Considerations

Credit card regex patterns are usually fast because they mostly rely on fixed lengths, digit classes and simple alternations.

Performance problems are more likely when a pattern contains nested quantifiers, ambiguous alternatives or attempts to parse too much context.

Keep validation regexes simple, anchored and specific. This improves readability, performance and security.

Frequently Asked Questions

Which credit card regex should I use for a payment form?

Use a flexible pattern that accepts digits with optional spaces or hyphens, then normalize the value before deeper validation.

For real payments, regex should only be the first filter. The card number must still be checked with the Luhn algorithm and verified by your payment provider.

Can regex detect Visa, Mastercard or American Express?

Yes, regex can detect common card networks by their prefixes and lengths.

However, issuer ranges change over time, so brand-specific patterns should be reviewed periodically and should not replace payment-provider validation.

Why does my regex accept fake test card numbers?

Regex only checks the visible format of the number.

Many fake or test card numbers have a valid-looking structure, so they can match a regex even when they are not real usable cards.

Should I allow spaces and hyphens in card numbers?

Yes, most payment forms allow spaces because they make long card numbers easier to read and type.

A common approach is to accept spaces or hyphens in the form, then remove them before validation and payment processing.

Is it safe to search logs for credit card numbers with regex?

Regex can help detect potential card numbers in logs, but it should be used carefully.

Any detected values should be masked, removed or handled according to your security and compliance requirements.

Should credit card validation run in JavaScript or on the server?

Client-side validation is useful for instant feedback, but it must never be the only validation layer.

Server-side validation and payment-provider checks are required for any real payment workflow.

Continue learning

📘 Recommended guide

Regex Limitations

A regex is excellent for checking structure, format and character rules, but it does not understand business logic.

For credit cards, this means a regex can detect whether a number looks like a card number, but it cannot confirm that the card exists, belongs to a user or can be charged.

Use regex as a fast first filter, then rely on specialized validation rules, checksum algorithms and trusted server-side systems.

Read the complete guide →
📘 Recommended guide

Testing Regex

Credit card regex patterns should be tested with valid numbers, invalid prefixes, incomplete input, separators and realistic form entries.

Do not test only happy paths. Include compact numbers, spaced numbers, hyphenated numbers, mixed separators, too-short values and brand prefixes that should be rejected.

A good test set proves both sides of the pattern: it accepts valid formats and rejects malformed or dangerous input.

Read the complete guide →
📘 Recommended guide

Regex Compatibility

Most credit card patterns use simple syntax such as anchors, digit classes, groups and alternation, so they work well across JavaScript, PCRE, Python, Java and .NET.

Advanced examples using lookbehind, named groups or replacement syntax may behave differently depending on the regex engine.

Always test production patterns in the same language and regex engine used by your application.

Read the complete guide →
📘 Recommended guide

Regex Performance

Credit card patterns are usually fast because they rely on fixed lengths, digit classes and simple alternatives.

Performance problems appear when a regex becomes too broad, uses ambiguous alternatives or tries to parse too much context around the number.

For validation, keep the pattern anchored, explicit and focused on the input field instead of scanning large text blocks unnecessarily.

Read the complete guide →
📘 Recommended guide

Input Validation Best Practices

For payment forms, regex should be only one validation layer after input normalization and before server-side payment verification.

Normalize the value first by removing spaces and hyphens, then validate the format, then run checksum and provider-side checks.

Client-side regex validation improves the user experience, but sensitive payment validation must always be repeated server-side.

Read the complete guide →
📘 Recommended guide

Character Classes

Credit card patterns rely heavily on digit classes such as \d and explicit character classes to validate the expected input.

Understanding character classes makes it easier to read, customize and maintain payment-related regexes.

Read the complete guide →
📘 Recommended guide

Quantifiers

Most credit card regexes depend on quantifiers such as {4}, {16} or optional separators.

Learning how quantifiers work helps you build precise validation patterns without making them unnecessarily complex.

Read the complete guide →