Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of '4111111111111111' |
(?: |
Non-capturing group start: groups alternatives without capturing | Start of group for Visa cards |
4[0-9]{12} |
Visa cards: starts with 4, followed by 12 digits | 4111111111111 |
(?:[0-9]{3})? |
Optional group: 3 digits (Visa 16-digit cards) | 123 |
| |
Alternation: separates alternatives in the group | Separates Visa from MasterCard patterns |
5[1-5][0-9]{14} |
MasterCard: starts with 51-55, followed by 14 digits | 5555555555554444 |
| |
Alternation: separates alternatives in the group | Separates MasterCard from Amex patterns |
3[47][0-9]{13} |
Amex: starts with 34 or 37, followed by 13 digits | 378282246310005 |
| |
Alternation: separates alternatives in the group | Separates Amex from Diners Club patterns |
3(?:0[0-5]|[68][0-9])[0-9]{11} |
Diners Club: starts with 300-305 or 36-38, followed by 11 digits | 30569309025904 |
| |
Alternation: separates alternatives in the group | Separates Diners Club from Discover patterns |
6(?:011|5[0-9]{2})[0-9]{12} |
Discover: starts with 6011 or 65, followed by 12 digits | 6011111111111117 |
| |
Alternation: separates alternatives in the group | Separates Discover from JCB patterns |
35(?:2[89]|[3-8][0-9])[0-9]{13} |
JCB: starts with 3528-3529 or 353-358, followed by 13 digits | 3530111333300000 |
) |
Non-capturing group end | End of group for all card patterns |
$ |
Anchor: asserts position at end of the string | End of '4111111111111111' |
Matches
4111111111111411111111111111155555555555544443782822463100053056930902590460111111111111173530111333300000
Does not match
1234567890123456411111111111111510510510510510034000000000000065000000000000003527000000000000abc123def456
Common pitfalls
- Forgetting to anchor with ^ and $ may match partial strings or invalid prefixes/suffixes
- Not accounting for optional groups (e.g., Visa 13 vs 16 digits) can cause mismatches
- Assuming all card numbers are 16 digits; patterns include 13, 14, 15, and 16-digit cards
- Overlooking that Diners Club and JCB have specific ranges beyond the initial digits
Performance notes
The regex is well-structured with non-capturing groups and alternations ordered by likelihood, minimizing backtracking. However, very long strings (e.g., 1000+ chars) may cause performance issues due to the {n} quantifiers. Anchoring with ^ and $ is critical to prevent partial matches.