Regular expression for 2 or 5 digits
Use 3 optional digits:
^\d{2}\d{3}?$
Note that some regex engines will interpret the ?
after any repetition modifier (even a fixed one) as an ungreedy modifier, which seems to cause problems for the case of two digits. If you experience this, use:
^\d{2}(?:\d{3})?$
You can read up on some regex basics in this great tutorial.
By the way, the above is effectively equivalent (but marginally more efficient) to this one using alternation:
^(?:\d{2}|\d{5})$
(Just for the sake of showing you another regex concept.)