Java us postal zip code validation
https://www.theitroad.com
To validate US postal (ZIP) codes using Java regular expressions, you can use the following regex pattern:
^\d{5}(-\d{4})?$
Here's a breakdown of what the regex pattern means:
^- Match the start of the string\d{5}- Match five digits(-\d{4})?- Optionally, match a hyphen followed by four digits$- Match the end of the string
Here's an example Java code that uses the above regular expression pattern to validate US postal codes:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static boolean isUSPostalCodeValid(String postalCode) {
String regex = "^\\d{5}(-\\d{4})?$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(postalCode);
return matcher.matches();
}
public static void main(String[] args) {
String postalCode1 = "12345";
String postalCode2 = "12345-6789";
String postalCode3 = "1234";
String postalCode4 = "12345-";
String postalCode5 = "1234-56789";
System.out.println(postalCode1 + " is " + (isUSPostalCodeValid(postalCode1) ? "valid" : "invalid"));
System.out.println(postalCode2 + " is " + (isUSPostalCodeValid(postalCode2) ? "valid" : "invalid"));
System.out.println(postalCode3 + " is " + (isUSPostalCodeValid(postalCode3) ? "valid" : "invalid"));
System.out.println(postalCode4 + " is " + (isUSPostalCodeValid(postalCode4) ? "valid" : "invalid"));
System.out.println(postalCode5 + " is " + (isUSPostalCodeValid(postalCode5) ? "valid" : "invalid"));
}
}
This code will output:
12345 is valid 12345-6789 is valid 1234 is invalid 12345- is invalid 1234-56789 is invalid
As you can see, the code correctly identifies which postal codes are valid according to the US postal code format.
