正则表达式 - 如何验证由“ - ”分隔的一组数字?

时间:2013-06-12 10:15:46

标签: php regex

我正在试图弄清楚如何验证格式化的数字:XXXX或XXXX-XXXX

我试过

/^\d{4}(-{1}\d{4})?/i

但它仅验证XXXX-XXXX格式,而不验证XXXX。

提前致谢

3 个答案:

答案 0 :(得分:1)

进行验证时不需要捕获组:

^\d{4}(?:-\d{4})?$
^\/\ /\ /^\/\ /^^^
| | |  | | | | ||`-- end of string
| | |  | | | | |`-- previous is optional (non-capture group of `-` and 4 numbers 0-9)
| | |  | | | | `-- end of non-capture group
| | |  | | | `-- exactly 4 of previous (any number 0-9)
| | |  | | `-- any number 0-9
| | |  | `-- just `-`
| | |  `-- non-capture group
| | `-- exactly 4 of previous (any number 0-9)
| `-- any number 0-9
`-- start of string

答案 1 :(得分:0)

试试这个:

/\d{4}(-\d{4})?/

DEMO:http://regexr.com?356sf

答案 2 :(得分:0)

我试过这个:

^\d{4}(-\d{4})?

此处:http://regexpal.com/

您可以在第一个区域中编写正则表达式并测试第二个区域中的数字。

适用于1234和1234-1234(任何数字)。

相关问题