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}$
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}$
Try the following:
^([0-9]{4})?$
^
- start of line
([0-9]{4})?
- four numbers, optionally (because of the ?
)
$
- end of line
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!
You do not need to use regular expressions for something as simple as matching a year:
if (ctype_digit($year) && strlen($year) === 4) {
echo 'This is a year';
} else {
echo 'Not a year';
}