The string, "K2S 1W3333333" can be caught be checking for a fixed string length. See the below snippet, particularly the line
int len = postal.length();
if ((len == 7) && (postal.charAt(3) != ' '))
and/or ...
} else if ((len != 6) && (len != 7)) {
After reading some of the basic rules for Postal codes in Canada, here's a quick snippet that checks for validity:
public class App {
public static boolean checkCode(String postal) {
if (postal == null || postal.isEmpty()) {
System.out.println("Empty postal code");
return false;
}
int len = postal.length();
if ((len == 7) && (postal.charAt(3) != ' ')) {
System.out.println("Invalid postal code length (7 characters requires space in middle of code)");
return false;
} else if ((len != 6) && (len != 7)) {
System.out.println("Invalid postal code length (6 characters required)");
return false;
}
if (len == 7) {
postal = postal.replace(" ", "");
len = postal.length();
}
final char[] invalidUpLetters = { 'D', 'F', 'I', 'O', 'Q', 'U' };
final char[] invalidLowLetters = { 'd', 'f', 'i', 'o', 'q', 'u' };
for (int i = 0; i < len; ++i) {
final char c = postal.charAt(i);
if (i % 2 == 0) {
if (!Character.isLetter(c)) {
System.out.println("Invalid letter at postal code string index: " + i);
return false;
}
for (int j = 0; j < invalidUpLetters.length; ++j) {
if ((c == invalidUpLetters[j]) || (c == invalidLowLetters[j])) {
System.out.println("Invalid letter used in postal code, string index: " + i);
return false;
}
}
if ((i == 0) && (c == 'W' || c == 'w' || c == 'Z' || c == 'z')) {
System.out.println("First position letter cannot be W or Z");
return false;
}
} else if ((i % 2 == 1) && (!Character.isDigit(c))) {
System.out.println("Invalid digit at postal code string index: " + i);
return false;
}
}
return true;
}
public static void main(String[] args) {
args = new String[] { "K2S 1W3333333", "K2S 1W3", "K2S1W3" };
System.out.println("is valid postal? " + (checkCode(args[0]) ? "Yes" : "No"));
System.out.println("is valid postal? " + (checkCode(args[1]) ? "Yes" : "No"));
System.out.println("is valid postal? " + (checkCode(args[2]) ? "Yes" : "No"));
}
}
This is an extensive check that include logic for checking for letters / digits at the respective indexes, as well as if the first letter is valid or not, as well as if the letters are/supposed to be excluded all together. The snippet also includes a check for adding a space in the middle of the 6-digit postal code or not. Be wary of Characters!
You could also remove the System.out.println()'s from the checkCode() method and stick to using booleans - this would help clear some of the debug and make the code easier to read - for the sake of simplicity (just needed to use the method to check whether a string is a valid Canada postal code or not).
Edit: If you're getting more variation of input postal codes, such as "K2S, 1W3" as stated in your original post, consider normalizing/parsing out characters as shown in my snippet to more easily read postal codes.
Cheers