Credit Card Number with Network Detection Regex for Java
/^(?:(4)[0-9]{12}(?:[0-9]{3,6})?|(5[1-5][0-9]{14}|2(?:2[2-9][1-9]|[3-6][0-9]{2}|7[01][0-9]|720)[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|(6(?:011|5[0-9]{2})[0-9]{12,15})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/What this pattern does
This page provides a comprehensive, battle-tested regular expression for matching credit card number with network detection, ported and verified for Java. Identity and credential patterns need both correctness and safety, since they're frequent targets for adversarial input. The snippet below is ready to drop into your Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.
Java Implementation
// Credit Card Number with Network Detection
// ReDoS-safe | RegexVault — Identity & PII > Financial PII
import java.util.regex.Pattern;
public class CreditCardNumberWithNetworkDetectionValidator {
private static final Pattern PATTERN =
Pattern.compile("^(?:(4)[0-9]{12}(?:[0-9]{3,6})?|(5[1-5][0-9]{14}|2(?:2[2-9][1-9]|[3-6][0-9]{2}|7[01][0-9]|720)[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|(6(?:011|5[0-9]{2})[0-9]{12,15})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$");
public static boolean validate(String input) {
return PATTERN.matcher(input).matches();
}
// Example
public static void main(String[] args) {
System.out.println(validate("4111111111111111")); // true
}
}Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
4111111111111111 | 1234567890123456 |
5500005555555559 | 411111111111 |
378282246310005 | 411111111111111111111 |
30569309025904 | — |
6011111111111117 | — |
When to use this pattern
This pattern is drawn from the Identity & PII > Financial PII category and carries a ReDoS-safe certification. That matters for Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
PCI-DSS requires Luhn validation, not just format matching. Storage of card data requires quarterly security assessments and annual PCI-DSS certification. Use a payment gateway (Stripe, Adyen) to avoid handling raw PANs.
Technical Notes
Capture groups: 1=Visa, 2=Mastercard, 3=Amex, 4=Diners Club, 5=Discover, 6=JCB. PCI-DSS: never store CVV, never log PANs, always encrypt stored card data, use tokenization for recurring billing.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern