Regex, Number or Empty

Can someone show me how to match 4 digits or nothing in Regex? I use RegexBuddy, and so far I have come up with this, but the help text says: β€œOr match the regular expression number 2 below - the whole match attempt fails if this error doesn't match” regarding the pattern after the pipe.

I would like either of the two to give a positive result.

^\d{4}|$ 
+6
source share
3 answers

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 ^$

+11
source

I think your approach sounds. You need to remember operator priority and use

 ^(\d{4}|)$ 

or

 ^\d{4}$|^$ 
+2
source

I don’t think if he needs OR

 ^(\d{4})?$ 
+1
source

Source: https://habr.com/ru/post/954407/


All Articles