^\d{5}(?:[-\s]\d{4})?$
^
= Start of the string.
\d{5}
= Match 5 digits (for condition 1, 2, 3)
(?:…)
= Grouping
[-\s]
= Match a space (for condition 3) or a hyphen (for condition 2)
\d{4}
= Match 4 digits (for condition 2, 3)
…?
= The pattern before it is optional (for condition 1)
$
= End of the string.
This is from the following question, hope it helps
regex for zip-code
For the optiona startingil letter use
[A-Z]?
to make the letter optional. {1}
is redundant. (Of course you could also write [A-Z]{0,1}
which would mean the same, but that's what the ?
is there for.)
I think it should go after the ^
but haven't had a chance to test