【问题标题】:Validating credit card number using regular expression使用正则表达式验证信用卡号
【发布时间】:2019-02-26 10:53:25
【问题描述】:

信用卡号格式为:“nnnn nnnn nnnn nnnn”

我用这个模式测试了下面四个字符串,但是 temp3 字符串意外返回 true。

我不知道怎么了。我正在使用的正则表达式应该准确地验证四位数字和一个空格,但是 temp3 尽管不匹配此模式,但仍返回 true。

String temp1 = " adfs 1111 2222 3333 4444 fadad";  // outer test
String temp2 = "11 11 2222 3333 4444"; // inner test
String temp3 = "11111 2222 3333 4444"; // inner test
String temp4 = "1111 2a222 3333 4444"; // inner test

public String chkContainCardno(String inputstr) {

    Pattern p = Pattern.compile("[0-9]{4}\\s[0-9]{4}\\s[0-9]{4}\\s[0-9]{4}");
    Matcher m = p.matcher(inputstr);

    if (m.find()) {
        return m.group(0);
    } else {
        return ErrMsg.Does_Not_Contain_Card_No;
    }
}

[测试结果]

temp1 : adfs 1111 2222 3333 4444 fadad : true 1111 2222 3333 4444

temp2:11 11 2222 3333 4444:假

temp3 : 11111 2222 3333 4444 : true 1111 2222 3333 4444 我不明白

temp4:1111 2a222 3333 4444:假

【问题讨论】:

  • 第 1 和第 3 是唯一匹配模式的输入以查找 4 组 4 位数字
  • 有一个实际的算法来检查信用卡是否是真实的信用卡号,称为Luhn algorithm

标签: regex credit-card


【解决方案1】:

第三个测试通过了,因为您的模式周围没有锚点。您应该在任一端添加\b,即"\\b[0-9]{4}\\s[0-9]{4}\\s[0-9]{4}\\s[0-9]{4}\\b",以强制在单词边界内匹配。

【讨论】:

    【解决方案2】:

    你可以用这个:

    "(\\b\\d{4}\\s\\d{4}\\s\\d{4}\\s\\d{4}\\b)"
    

    b - 单词边界

    d - 数字

    【讨论】:

      猜你喜欢
      • 2010-11-30
      • 2015-09-14
      • 2018-08-15
      • 2018-02-15
      • 2016-07-31
      • 2012-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多