Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java regex for US State Validation

Tags:

java

regex

I wrote this java method to do regex and missing something because it fails for all conditions. I am new to regex and unable to figure out whats causing it to fail for everything. Can some expert help me.

public static boolean isStateValid(String state){
        String expression = "/^(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])*$/";
        CharSequence inputStr = state;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            return true;
        }else{
            return false;
        }
    }

Changed to this after reading comments and stil it isnt working

public static boolean isStateValid(String state) {
        CharSequence inputStr = state;
        Pattern pattern = Pattern
                .compile("AL|AK|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NC|ND|NE|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY|al|ak|ar|az|ca|co|ct|dc|de|fl|ga|hi|ia|id|il|in|ks|ky|la|ma|md|me|mi|mn|mo|ms|mt|nc|nd|ne|nh|nj|nm|nv|ny|oh|ok|or|pa|ri|sc|sd|tn|tx|ut|va|vt|wa|wi|wv|wy");
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }
like image 327
juniorbansal Avatar asked Jan 24 '26 07:01

juniorbansal


1 Answers

A lot of things.

First it is not perl. Remove leading and trailing slashes. Second, why non-capturing group? I mean (?: You do not need group at all here. Third why so complicated? Just say something like

Pattern.compile("AL|AK|AR|AZ|CA");

etc., all states. Your optimization does not have any benefits. It just makes regex more complicated.

like image 160
AlexR Avatar answered Jan 26 '26 19:01

AlexR