2

i attempted to port the code in this answer to Java: PHP VIN number validation code

i understand that String.matches in Java is a bit temperamental and i'm very unfamiliar with regular expressions. here is the code:

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)));
}

anyone familiar with a proper way to use this regex in Java?

Community
  • 1
  • 1
moonlightcheese
  • 10,664
  • 9
  • 49
  • 75
  • If removing the slashes don't work, print out vin before you exit. It looks like vin should all be lower case. If all else fails, use a debugger. –  Feb 16 '11 at 20:19

2 Answers2

6

Remove the slashes from the regex. In other words:

if(!vin.matches("^[^\\Wioq]{17}$")) { 
Thomas
  • 4,889
  • 4
  • 24
  • 19
  • @moonlightcheese - Just a fyi if you don't convert the vin to lower case (as that code from your link), any I,O,or Q will match in the negative character class. –  Feb 16 '11 at 20:43
0

Try this at home:

class Vin { 
   public static void main( String ... args ) { 
      String vin = "1M8GDM9A_KP042788";
      if(!vin.matches("[^\\Wioq]{17}")) { //the offending code, always fails
        System.out.println("vininfo did not pass regex");
      } else { 
        System.out.println("works");
     }
   }
}

Prints:

$java Vin 
works

You don't need the /^ and $/

OscarRyz
  • 196,001
  • 113
  • 385
  • 569