This tutorial shows who to run an simple Regular Expression in Java. First it defines 2 simple Regular Expressions or RegExp to test if a String is a valid 5 digit or 9 digit zipcode. Then the main method defines a list of Strings containing the possible zip code to test. Finally, the code loops through the Strings and test if any matches the 2 patterns. If it does a message with the matching regexp is written in the output, else just an error is written.
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class RegexpPostalCode {
// 5 digits pattern
public static final Pattern PATTERN_5_DIGITS = Pattern.compile("\\d{5}");
// 9 digits pattern
public static final Pattern PATTERN_9_DIGITS = Pattern.compile("\\d{5}-\\d{4}");
public static void main(String[] argv) {
// Define the list
List<String> myList = new ArrayList<String>();
// Add the values
myList.add("95012");
myList.add("11");
myList.add("abcde");
myList.add("abcde-abcd");
myList.add("95012-1234");
myList.add("95012.1234");
// Loop on the list
for (String current : myList) {
// Test the 5 digits pattern
if (PATTERN_5_DIGITS.matcher(current).matches()) {
System.out.println(current + " is a 5 digit zipcode!");
} // Test the 9 digits pattern
else if (PATTERN_9_DIGITS.matcher(current).matches()) {
System.out.println(current + " is a 9 digit zipcode!");
} else {
System.out.println(current + " is not a zipcode.");
}
}
}
}
95012 is a 5 digit zipcode!
11 is not a zipcode.
abcde is not a zipcode.
abcde-abcd is not a zipcode.
95012-1234 is a 9 digit zipcode!
95012.1234 is not a zipcode.