import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\\d{3})\\d{11})$";
final String string = "4242424242424242\n"
+ "4012888888881881\n"
+ "4000056655665556\n"
+ "5555555555554444\n"
+ "5200828282828210\n"
+ "5105105105105100\n"
+ "378282246310005\n"
+ "371449635398431\n"
+ "6011111111111117\n"
+ "6011000990139424\n"
+ "30569309025904\n"
+ "38520000023237\n"
+ "3530111333300000\n"
+ "3566002020360505\n"
+ "8942424242424242\n"
+ "63942424242\n"
+ "445299295665920\n\n"
+ "Visa\n"
+ "Visa\n"
+ "Visa (debit)\n"
+ "MasterCard\n"
+ "MasterCard (debit)\n"
+ "MasterCard (prepaid)\n"
+ "American Express\n"
+ "American Express\n"
+ "Discover\n"
+ "Discover\n"
+ "Diners Club\n"
+ "Diners Club\n"
+ "JCB\n"
+ "JCB\n"
+ "Invalid\n"
+ "Invalid\n"
+ "Invalid";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html