我正在通过 Android 中用户输入的号码进行信用卡类型检测。 现在,Dankort卡以前缀“4571”和 VISA 开头卡以前缀“4”开头。
在开始输入号码时,如果用户以 4 开头,那么我不想显示类型,因为它可能是 Dankort 或 VISA。现在如果第二个输入的数字不是5,那么我想显示VISA。如果用户输入 457,那么我仍然不会显示任何类型。如果用户输入 4571,那么我将显示 Dankort。
基本上,我想要逐个字符搜索,但我无法做到这一点
卡片的startsWith前缀存储在ArrayList中。到目前为止我所尝试的是。 遍历前缀列表并检查用户输入的号码的开头。如果用户输入的号码以列表中提供的前缀开头。然后我将其添加到一个临时列表中,如果临时列表大小等于 1,则我相信已找到卡类型。
例如:请参阅下面的代码。仅用于演示目的
List<String> list = new ArrayList();
list.add("4");
list.add("4570");
List<String> matchList = new ArrayList();
for(int i=0; i<list.size(); i++) {
if(cardNumber.startsWith(list.get(i))) {
matchList.add(list.get(i));
}
}
但这不起作用,就好像我开始输入并只输入“4”,然后它还显示 VISA 卡。如果您需要更多说明,请告诉我
最佳答案
您可以使用如下正则表达式来做到这一点:
^(4571)|^(4(?:[0-46-9]|5(?:[0-68-9]|7[02-9])))
如果第 1 组匹配,则为 Dankort。
如果第 2 组匹配,则获得签证。
否则未知。
作为代码:
String regex = "^(4571)" + // matches leading 4571 (Dankort)
"|^(4(?:[0-46-9]" + // matches leading 4 followed by not 5 (Visa)
"|5(?:[0-68-9]" + // matches leading 45 followed by not 7 (Visa)
"|7[02-9])))" + // matches leading 457 followed by not 1 (Visa)
"|^(5)" + // matches leading 5 (MasterCard)
"|^(6)" + // matches leading 6 (Discover Card)
"|^(37)" + // matches leading 37 (American Express)
"|^(38)"; // matches leading 38 (Diners Club)
Matcher m = Pattern.compile(regex ).matcher(cardNumber);
if (! m.find()) {
// unknown
} else if (m.start(1) != -1) {
// Dankort
} else if (m.start(2) != -1) {
// Visa
} else if (m.start(3) != -1) {
// MasterCard
} else if (m.start(4) != -1) {
// Discover Card
} else if (m.start(5) != -1) {
// American Express
} else if (m.start(6) != -1) {
// Diners Club
} else {
// unknown
}
关于java - 在 Android 中检查特定字符串是否有多个startsWith前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59643720/