Credit Card Number Patterns
What you'll learn: You'll learn how to build regex patterns that validate the specific digit structures of major credit card types like Visa, MasterCard, and American Express.
Understanding Credit Card Number Structure
Credit card numbers aren't random—each card type follows a predictable pattern based on starting digits and total length. Visa cards start with 4 and have 13 or 16 digits. MasterCard begins with 51-55 or 2221-2720 and always has 16 digits. American Express starts with 34 or 37 and has exactly 15 digits.
Think of these patterns like postal codes for different regions—the prefix tells you the issuer, and the length confirms the format.
Building the Patterns
For Visa, you need a pattern that matches a 4 followed by 12 or 15 more digits:
Pattern visaPattern = Pattern.compile("^4\\d{12}(\\d{3})?$");
Matcher visaMatcher = visaPattern.matcher("4532015112830366");
boolean isVisa = visaMatcher.matches(); // true
For MasterCard (simplified to 51-55 range):
Pattern masterCardPattern = Pattern.compile("^5[1-5]\\d{14}$");
Matcher mcMatcher = masterCardPattern.matcher("5425233430109903");
boolean isMasterCard = mcMatcher.matches(); // true
For American Express:
Pattern amexPattern = Pattern.compile("^3[47]\\d{13}$");
Matcher amexMatcher = amexPattern.matcher("378282246310005");
boolean isAmex = amexMatcher.matches(); // true
Breaking Down the Syntax
^and$anchor the pattern to match the entire string\\d{n}matches exactly n digits(\\d{3})?makes the last three digits optional (for Visa's 13 or 16 length)[1-5]matches any single digit in that range3[47]matches 34 or 37 specifically
Key Takeaway: Credit card validation patterns combine prefix matching with exact length requirements using anchors, digit ranges, and quantifiers—remember that these patterns check format structure only, not whether the card is actually valid (which requires the Luhn algorithm).