import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^\n"
+ "(?:4[0-9]{12}(?:[0-9]{3})?\n"
+ " |\n"
+ "5[1-5][0-9]{14}\n"
+ "|\n"
+ "6(?:011|5[0-9][0-9])[0-9]{12}\n"
+ "|\n"
+ "3[47][0-9]{13}\n"
+ "|\n"
+ "3(?:0[0-5]|[68][0-9])[0-9]{11}\n"
+ "|\n"
+ "(?:2100|2131|1800|35\\d{3})\\d{11})\n"
+ "$";
final String string = "#American Express\n"
+ "370517943574132\n"
+ "372714451742486\n"
+ "370010255141385\n"
+ "341263547614307\n"
+ "343874494387669\n\n"
+ "#VISA\n"
+ "4024007125780444\n"
+ "4439944519233615\n"
+ "4658355677043536\n"
+ "4532926168018906\n"
+ "4532249806735728\n\n"
+ "#MasterCard\n"
+ "5524097521691644\n"
+ "5367170623993901\n"
+ "5553103980950937\n"
+ "5549194987582424\n"
+ "5141794881796756\n\n"
+ "#JCB 15 digits\n"
+ "180078244412845\n"
+ "210013400722277\n"
+ "210082510016250\n"
+ "180056142071970\n"
+ "210043823226606\n\n"
+ "#JCB\n"
+ "3158822586903214\n"
+ "3088687202983378\n"
+ "3158899851849561\n"
+ "3096803356450490\n"
+ "3337852908456769\n\n"
+ "#Dinners Club\n"
+ "30193567772121\n"
+ "30131361923813\n"
+ "30198560976769\n"
+ "30260244203356\n"
+ "36297440059376\n\n\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.CASE_INSENSITIVE | Pattern.COMMENTS);
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