Java/Regular Expressions/ZIP Code
Match Zip
/*
#Japanese postal codes
zipJP=^\d{3}-\d{4}$
#US postal codes
zipUS=^\d{5}\p{Punct}?\s?(?:\d{4})?$
#Dutch postal code
zipNL=^[0-9]{4}\s*[a-zA-Z]{2}$
#Argentinean postal code
zipAR=^\d{3}-\d{4}$
#Swedish postal code
zipSE=^(s-|S-){0,1}[0-9]{3}\s?[0-9]{2}$
#Canadian postal code
zipCA=^([A-Z]\d[A-Z]\s\d[A-Z]\d)$
#UK postal code
zipUK=^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$
*/
public class MatchZipCodes {
public static void main(String args[]) {
isZipValid("45643-4443");
isZipValid("45643");
isZipValid("443");
isZipValid("45643-44435");
isZipValid("45643 44435");
}
public static boolean isZipValid(String zip) {
boolean retval = false;
String zipCodePattern = "\\d{5}(-\\d{4})?";
retval = zip.matches(zipCodePattern);
String msg = "NO MATCH: pattern:" + zip + "\r\n regex: "
+ zipCodePattern;
if (retval) {
msg = "MATCH : pattern:" + zip + "\r\n regex: "
+ zipCodePattern;
}
System.out.println(msg + "\r\n");
return retval;
}
}
Match Zip Codes
public class Main {
public static void main(String[] a) {
String zip = "1234-123";
String zipCodePattern = "\\d{5}(-\\d{4})?";
boolean retval = zip.matches(zipCodePattern);
}
}