【发布时间】: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