Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex to filter year of fixed length 0 or 4 digit

i want to filter year using regex in php or javascript.

which contain only number and its length is 0(if not input) or 4 if(insert) it is not accept 1, 2 or 3 length for ex 123.

i know regex for 0 to 4 digit which is ^[0-9]{0,4}$ or ^\d{0,4}$

like image 827
Piyush Avatar asked Aug 31 '25 03:08

Piyush


2 Answers

Try the following:

^([0-9]{4})?$

^ - start of line

([0-9]{4})? - four numbers, optionally (because of the ?)

$ - end of line

like image 99
Benjamin Gruenbaum Avatar answered Sep 02 '25 17:09

Benjamin Gruenbaum


I know this question has already been answered but just to be more clear and as an alternate solution i would come up with this:

In your pattern:

^[0-9]{0,4}$

{0,4} will allow to match numbers of length 0, 1, 2, 3 and 4. To eliminate length 1, 2 and 3 you can also use something like:

^\d{4}?$

Here:

^    = beginning of line
\d   = any digit - equivalent of [0-9]
{4}  = exactly four times
?    = makes the preceding item optional
$    = end of line

Hope it helps!

like image 27
NeverHopeless Avatar answered Sep 02 '25 18:09

NeverHopeless