Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of string |
(?: |
Non-capturing group start | Start of group |
4 |
Literal digit 4 (Visa card prefix) | 4 |
[0-9]{12} |
Exactly 12 digits (0-9) | 123456789012 |
(?: |
Non-capturing group start | Start of optional group |
[0-9]{3} |
Exactly 3 digits (0-9) | 345 |
)? |
End of group, quantifier: 0 or 1 occurrence | Optional 3 digits |
| |
Alternation (OR operator) | OR |
5 |
Literal digit 5 (MasterCard prefix) | 5 |
[1-5] |
Digit in range 1-5 (MasterCard second digit) | 1 |
[0-9]{14} |
Exactly 14 digits (0-9) | 23456789012345 |
| |
Alternation (OR operator) | OR |
3 |
Literal digit 3 (Amex or Discover prefix) | 3 |
[47] |
Digit 4 or 7 (Amex second digit) | 4 |
[0-9]{13} |
Exactly 13 digits (0-9) | 4567890123456 |
| |
Alternation (OR operator) | OR |
35 |
Literal digits 3 and 5 (Discover prefix) | 35 |
(?: |
Non-capturing group start | Start of group |
0[0-5] |
Digit 0 followed by 0-5 | 05 |
| |
Alternation (OR operator) | OR |
[68][0-9] |
Digit 6 or 8 followed by any digit | 60 |
) |
End of non-capturing group | End of group |
[0-9]{11} |
Exactly 11 digits (0-9) | 12345678901 |
) |
End of non-capturing group | End of group |
$ |
Anchor: asserts position at end of the string | End of string |
Matches
411111111111111142222222222225105105105105100555555555555444434000000000000937828224631000535301113333000003566002020360505
Does not match
41111111111111142222222222222222500510510510510060111111111111173300000000000093882822463100053630111333300000353011133330000
Common pitfalls
- Forgetting to anchor with ^ and $, allowing partial matches in longer strings.
- Assuming this matches all valid credit card numbers (e.g., Diners Club, JCB are missing).
- Not accounting for spaces or hyphens in input (this pattern requires raw digits only).
- Misinterpreting the optional group for Visa cards (e.g., 4 digits total 13 or 16).
- Overlooking that Amex numbers are 15 digits (this pattern matches 15-digit Amex numbers).
Performance notes
The pattern is well-structured with no nested quantifiers or backtracking risks. The alternation is linear and efficient. No catastrophic backtracking expected. Anchoring with ^ and $ ensures full-string matching.