原文: https://howtodoinjava.com/regex/java-regex-validate-credit-card-numbers/

在此 Java 正则表达式教程中,我们将学习使用正则表达式来验证信用卡号。 我们将从多个提供商(例如 VISA,Mastercard,Amex 和 Diners 等)了解号码格式和信用卡号验证。

1. 有效的信用卡号格式

在实际的信用卡上,压纹卡号的数字通常分为四组。 这使得卡号更易于人类阅读。 每个信用卡公司都使用此数字格式。

我们将利用每个公司之间的格式差异来允许用户输入数字而无需指定公司。 可以从号码中确定公司。 每个公司的格式为:

  • Visa:13 或 16 位数字,以 4 开头。
  • Mastercard:从 51 到 55 开头的 16 位数字。
  • Discover:从 6011 或 65 开始的 16 位数字。
  • American Express:15 位数字,以 34 或 37 开头。
  • Diners Club :14 位数字,从 300 到 305、36 或 38 开头。
  • JCB :15 位数字,以 2131 或 1800 开头,或 16 位数字,以 35 开头。

下面给出的正则表达式假设在执行有效数字检查之前,我们将明确搜索并替换所有空格和连字符。

输入中去除了空格和连字符后,下一个正则表达式将检查信用卡号是否使用六家主要信用卡公司中的任何一家的格式。 它使用命名捕获来检测客户拥有的信用卡品牌

如果不需要确定卡的类型,则可以删除围绕每种卡类型的模式的六个捕获组,因为它们没有任何其他用途。

如果您仅接受某些品牌的信用卡,则可以从正则表达式中删除不接受的信用卡。 例如,删除 JCB 时,请确保删除最后剩余的“|” 在正则表达式中也是如此。 如果您的正则表达式以“|”结尾,它也将接受空字符串作为有效的卡号。

  1. Regex : ^(?:(?<visa>4[0-9]{12}(?:[0-9]{3})?)|
  2. (?<mastercard>5[1-5][0-9]{14})|
  3. (?<discover>6(?:011|5[0-9]{2})[0-9]{12})|
  4. (?<amex>3[47][0-9]{13})|
  5. (?<diners>3(?:0[0-5]|[68][0-9])?[0-9]{11})|
  6. (?<jcb>(?:2131|1800|35[0-9]{3})[0-9]{11}))$

在此 Wiki 页面中详细了解信用卡号码格式。

2. 信用卡号码验证示例

  1. public static void main(String[] args)
  2. {
  3. List<String> cards = new ArrayList<String>();
  4. //Valid Credit Cards
  5. cards.add("xxxx-xxxx-xxxx-xxxx"); //Masked to avoid any inconvenience unknowingly
  6. //Invalid Credit Card
  7. cards.add("xxxx-xxxx-xxxx-xxxx"); //Masked to avoid any inconvenience unknowingly
  8. String regex = "^(?:(?<visa>4[0-9]{12}(?:[0-9]{3})?)|" +
  9. "(?<mastercard>5[1-5][0-9]{14})|" +
  10. "(?<discover>6(?:011|5[0-9]{2})[0-9]{12})|" +
  11. "(?<amex>3[47][0-9]{13})|" +
  12. "(?<diners>3(?:0[0-5]|[68][0-9])?[0-9]{11})|" +
  13. "(?<jcb>(?:2131|1800|35[0-9]{3})[0-9]{11}))$";
  14. Pattern pattern = Pattern.compile(regex);
  15. for (String card : cards)
  16. {
  17. //Strip all hyphens
  18. card = card.replaceAll("-", "");
  19. //Match the card
  20. Matcher matcher = pattern.matcher(card);
  21. System.out.println(matcher.matches());
  22. if(matcher.matches()) {
  23. //If card is valid then verify which group it belong
  24. System.out.println(matcher.group("mastercard"));
  25. }
  26. }

3. 使用 Luhn 算法进行校验和验证

在处理顺序之前,您可以对信用卡号进行额外的验证检查。 信用卡号的最后一位数字是根据 Luhn 算法计算得出的校验和。 由于此算法需要基本的算术运算,因此无法使用正则表达式来实现。

下面是可用于使用 Luhn 算法运行校验和验证的方法。 此函数采用一个以信用卡号为参数的字符串。 卡号只能由数字组成。

实际算法在数字数组上运行,计算校验和。 如果总和模 10 为零,则卡号有效。 如果不是,则该数字无效。

我从 Google 代码中获取了 Luhn Algo 的参考实现。

  1. public class Luhn
  2. {
  3. public static boolean Check(String ccNumber)
  4. {
  5. int sum = 0;
  6. boolean alternate = false;
  7. for (int i = ccNumber.length() - 1; i >= 0; i--)
  8. {
  9. int n = Integer.parseInt(ccNumber.substring(i, i + 1));
  10. if (alternate)
  11. {
  12. n *= 2;
  13. if (n > 9)
  14. {
  15. n = (n % 10) + 1;
  16. }
  17. }
  18. sum += n;
  19. alternate = !alternate;
  20. }
  21. return (sum % 10 == 0);
  22. }
  23. }

如果需要,可以随意修改上述代码示例以匹配上述正则表达式中的其他验证规则。

学习愉快!