Java中的正则表达式

moo*_*ese 2 java regex string validation

我试图将此答案中的代码移植到Java: PHP VIN编号验证代码

据我所知,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)));
}
Run Code Online (Sandbox Code Playgroud)

有谁熟悉在Java中使用这个正则表达式的正确方法?

Tho*_*mas 6

从正则表达式中删除斜杠.换一种说法:

if(!vin.matches("^[^\\Wioq]{17}$")) { 
Run Code Online (Sandbox Code Playgroud)