我尝试将此答案中的代码移植到 Java: PHP VIN number validation code
我知道Java中的String.matches有点不稳定,而且我对正则表达式非常不熟悉。这是代码:
public boolean validateVIN(String vin) {
vin = vin.toLowerCase();
if(!vin.matches("/^[^\\Wioq]{17}$/")) { //the offending code, always fails
Log.e("vininfo", "did not pass regex");
return false;
}
int[] weights = { 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 };
//array positions coorespond to the 26 letters of the alphabet
int[] transliterations = { 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 0, 7, 0, 9, 2, 3, 4, 5, 6, 7, 8, 9 };
int sum = 0;
String checkdigit = ".";
for(int i=0; i < vin.length(); i++) {
//add transliterations * weight of their positions to get the sum
int temp = 0;
temp = vin.charAt(i);
if(temp < 58) {
sum += (temp-48)*weights[i];
Log.e("vinsum.num", String.valueOf(sum));
} else {
sum += transliterations[temp-97]*weights[i];
Log.e("vinsum.chr", String.valueOf(sum));
}
}
if(checkdigit.equals("10")) {
checkdigit = "x";
} else {
//find checkdidgit by taking the mod of the sum
checkdigit = String.valueOf(sum % 11);
}
Log.i("vininfo", "checkdigit: "+checkdigit+" ... VIN[8]: "+vin.substring(8,9));
return (checkdigit.equals(vin.substring(8, 9)));
}
有人熟悉在 Java 中使用此正则表达式的正确方法吗?
最佳答案
从正则表达式中删除斜杠。换句话说:
if(!vin.matches("^[^\\Wioq]{17}$")) {
关于java - Java中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5021461/