11

我已经阅读了这个问题,但是对于 Discover 卡,起始数字6011, 622126-622925, 644-649, 65不仅仅是6011, 65. (来源

对于发现卡,我从那个问题中选择了这个正则表达式^6(?:011|5[0-9]{2})[0-9]{12}$

我对其进行了修改,以覆盖6011&644-649但是65622126-622925构建正则表达式很难,因为我的正则表达式技能很差。

到目前为止6(?:011|5[0-9]{2}|[4][4-9][0-9]|[2]{2}[1-9])[0-9]{2}$,我有这个正则表达式,但它只检查622[1-9]**.

如何修改它以使其仅在622126-622925for 622***case 之间接受?

4

3 回答 3

15

这是您的正则表达式(演示)

^6(?:011\d{12}|5\d{14}|4[4-9]\d{13}|22(?:1(?:2[6-9]|[3-9]\d)|[2-8]\d{2}|9(?:[01]\d|2[0-5]))\d{10})$

不用说,我不会说这很漂亮或易于维护。我建议将数字解析为整数并使用您的编程语言进行检查。

您还应该使用Luhn 算法来检查信用卡号码是否有效,虽然理论上您可以使用正则表达式来执行此操作,但它会比这更糟糕。


请允许我一步一步地向你展示我是如何到达这个怪物的。首先,这里是你如何匹配每个范围:

6011        # matches 6011
65          # matches 65
64[4-9]     # matches 644-649
622(1(2[6-9]|[3-9]\d)|[2-8]\d{2}|9([01]\d|2[0-5]))  
            # matches 622126-622925

现在,您要匹配其余的数字:

6011\d{12}        # matches 6011 + 12 digits
65\d{14}          # matches 65 + 14 digits
64[4-9]\d{13}     # matches 644-649 + 13 digits
622(1(2[6-9]|[3-9]\d)|[2-8]\d{2}|9([01]\d|2[0-5]))\d{10}
                  # matches 622126-622925 + 10 digits

现在您可以组合所有四个,并添加行锚的开始和结束:

^(                  # match start of string and open group
 6011\d{12}|        # matches 6011 + 12 digits
 65\d{14}|          # matches 65 + 14 digits
 64[4-9]\d{13}|     # matches 644-649 + 13 digits
 622(1(2[6-9]|[3-9]\d)|[2-8]\d{2}|9([01]\d|2[0-5]))\d{10}
                    # matches 622126-622925 + 10 digits
)$                  # close group and match end of string

上面的最终产品是先前正则表达式的略微压缩版本,我还使组不捕获(这就是它们?:的用途)。

于 2012-11-21T19:44:58.693 回答
0

Here are your options:

  1. Hack your way through it and build a really complicated regex. Regexes are not suited for this sort of integer comparison so what you come up with will necessarily be long, uncomplicated and unmaintainable. See Regex for number check below a value and similar SO questions on this topic.
  2. Use integer comparison in your code.

For reference one such said complicated regex would be

62212[6-9]|6221[3-9]|622[1-8]|62291|62292[1-5]

于 2012-11-21T19:35:59.803 回答
0

即使这张票是 3 年前的,我也遇到了同样的任务,想分享一个 622126-622925 的正则表达式 :)

^(622[1-9]\\d(?<!10|11|9[3-9])\\d(?<!12[0-5]|92[6-9])\\d{10})$

它使用零宽度负向后查找来排除不期望的数字

于 2016-06-30T08:47:52.287 回答