Regex -如何验证一组由"-"分隔的数字


Regex - How to validate a set of numbers delimited by "-"?

我想弄清楚如何验证这样格式化的数字:XXXX或XXXX-XXXX

i tried

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

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

Thanks in advance

验证时不需要捕获组:

^'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

试试这个:

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

演示:http://regexr.com?356sf

我试了这个:

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

: http://regexpal.com/

你可以在第一个区域写正则表达式,在第二个区域测试数字。

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