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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With