Four digits or nothing:
^(?:\d{4}|)$
This is closest to what you tried to do.
I would do the following for a little shorter:
^(?:\d{4})?$
^\d{4}|$
This regular expression means:
^\d{4} OR $
The first will correspond only to any line that starts with 4 digits, and the second will report a match in everything (this corresponds to the end of the line, and since no character is specified, it will correspond to the end of all lines).
When you use a group, you get:
Either ^(?:\d{4})$ , or ^(?:)$ (Note that the "restrictions" of the OR operator are changed), which is equivalent to either ^\d{4}$ or ^$
Jerry source share