Regex, Number or Empty

14,516

Solution 1

Either 4 digits or nothing:

^(?:\d{4}|)$

This is closest to what you were trying to do.

I would go for the following for a slightly shorter one:

^(?:\d{4})?$

^\d{4}|$

That regex means either:

^\d{4} OR $

The first will match just any string that starts with 4 digits while the second will report a match on everything (it matches the end of a string, and since no character is specified, it will match the end of all strings).

When you're using a group, you're getting:

Either ^(?:\d{4})$ or ^(?:)$ (notice that the 'limits' of the OR operator changed), which is then equivalent to either ^\d{4}$ or ^$

Solution 2

I think your approach is sound. You do need to keep operator precedence in mind though and use either

^(\d{4}|)$

or

^\d{4}$|^$

Solution 3

I don't think if it needs OR

^(\d{4})?$
Share:
14,516
Grant
Author by

Grant

Updated on July 24, 2022

Comments

  • Grant
    Grant 4 months

    Can someone show me how to match 4 digits or nothing in Regex? I have been using RegexBuddy and so far i have come up with this but the help text is saying 'Or match regular expression number 2 below - the entire match attempt fails if this one fails to match' in regards to the pattern after the pipe.

    I would like either of the two to provide a positive match.

    ^\d{4}|$
    
  • Bob Vale
    Bob Vale about 9 years
    might be worth explaining that ^\d{4}|$ would match 1234a because the $ is not included in the first match
  • Jerry
    Jerry about 9 years
    @BobVale I might also add that ^\d{4}|$ as a whole will match anything because of $ :)