I need to validate a Canadian postal code (for example, M4B 1C7) using C# (.NET) regular expressions.
I need to validate a Canadian postal code (for example, M4B 1C7) using C# (.NET) regular expressions.
Canadian postal codes can't contain the letters D, F, I, O, Q, or U, and cannot start with W or Z:
[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]
If you want an optional space in the middle:
[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]
I suggest the following:
bool FoundMatch = false;
try {
FoundMatch = Regex.IsMatch(SubjectString, "\\A[ABCEGHJKLMNPRSTVXY]\\d[A-Z] ?\\d[A-Z]\\d\\z");
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}