使用正则表达式过滤固定长度0或4位数字的年份


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

我想在PHP或javascript中使用正则表达式过滤年份。

只包含数字,长度为0(如果不输入)或4(如果插入)。

不接受长度为1、2或3的ex123。

我知道0到4位数的正则表达式,即^[0-9]{0,4}$^'d{0,4}$

尝试如下:

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

^ -行起始

([0-9]{4})? -四个数字,可选(因为?)

$ - line end

我知道这个问题已经得到了回答,但只是为了更清楚,作为一个替代解决方案,我会想出这个:

In your pattern:

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

{0,4}将允许匹配长度为0、1、2、3和4的数字。要消除长度1、2和3,您还可以使用如下命令:

^'d{4}?$

:

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

希望有帮助!

对于像匹配年份这样简单的事情,您不需要使用正则表达式:

if (ctype_digit($year) && strlen($year) === 4) {
    echo 'This is a year';
} else {
    echo 'Not a year';
}