开发者

java regex for US State Validation

I wrote this java method to do regex and missing something because it fails for all conditions. I am new to regex and un开发者_StackOverflowable 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;
        }
    }


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.


It doesn't like the / characters at the beginning and end of the pattern. When I remove those, it works. Also, I don't think you want the * repetition character at the end.


This one is case-sensitive and includes the US territories:

^(?-i:A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$

However, I think using regex is over the top. Use a list or array of some kind.


Is this an exercise in practicing regular expressions, or something that will be used in a production environment?

If it's the latter, then using a lookup list will be better. In this case a regex obfuscates and overcomplicates what you're trying to do.


I haven't used this particular tool, but have used a commercial tool that's similar, but I think you would benefit from a tool like: http://sourceforge.net/projects/regexevaluator/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜