3

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

4

3 回答 3

9

Try the following:

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

^ - start of line

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

$ - end of line

于 2013-03-30T21:28:53.767 回答
3

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!

于 2013-03-31T16:35:17.397 回答
-1

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';
}
于 2013-03-30T21:51:25.983 回答