我正在试图弄清楚如何验证格式化的数字:XXXX或XXXX-XXXX
我试过
/^\d{4}(-{1}\d{4})?/i
但它仅验证XXXX-XXXX格式,而不验证XXXX。
提前致谢
答案 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)
答案 2 :(得分:0)
我试过这个:
^\d{4}(-\d{4})?
您可以在第一个区域中编写正则表达式并测试第二个区域中的数字。
适用于1234和1234-1234(任何数字)。