匹配正则表达式中的固定格式数字

时间:2009-03-20 14:03:29

标签: php regex

快速正则表达式问题(因为我很可怕)

我的字段只能包含:

XXXXXXXXXXXXXXXX-XXXX,其中X是实数。

如果正则表达式与PHP的正则表达式函数配合良好,可以获得奖励。

答案:

以下是 RoBorg 答案中的代码,供感兴趣的人使用。

if(!preg_match("/^\d{6}-?\d{4}$/", $var))
{
    // The entry didn't match
}

3 个答案:

答案 0 :(得分:8)

/^\d{6}-?\d{4}$/

那是

^     Start of string
\d{6} a digit, repeated exactly 6 times
-?    an optional "-"
\d{4} a digit, repeated exactly 4 times
$     end of string

答案 1 :(得分:1)

很快,它会是这样的: \d{6}-?\d{4}

您可能必须在PHP中转义连字符。

答案 2 :(得分:0)

如果你想要一个特定的数字(问题措辞最初有些含糊不清),请搜索(例如):

^123456-?7890$

如果使用该格式搜索任何 10位数字,请搜索:

^\d{6}-?\d{4}$

短划线后的?限定符表示“前一个实体出现0或1次”

相关问题