Q:

Regular expression for 2 or 5 digits

How do I write a regular expression that can match only numbers with 2 or 5 digits?
I have this so far but it matches any number with 2 to 5 digits. 
           ^\d{2,5}$

A:

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.)

