开发者

regular expressions in Java

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?


Remove the slashes from the regex. In other words:

if(!vin.matches("^[^\\Wioq]{17}$")) { 


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 $/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜