Regular Expression for number and dash

后端 未结 7 607
醉话见心
醉话见心 2020-12-15 23:08

Currently I write the regex like this: /^([\\d+]*-)+([\\d]*-)+([\\d])*$/

I want the result follow this pattern 00-123-456-789 or 0012

7条回答
  •  一生所求
    2020-12-15 23:40

    If your question needs the specific segment lengths you specify in your examples, you can use this:

    /^\d{2}-?\d{3}-?\d{3}-?\d{3}$/
    

    This will accept 00-123-456-789, but will allow for any dashes to be missing. If you want to allow only for all dashes or no dashes, then you could use this:

    /^\d{2}-\d{3}-\d{3}-\d{3}$|^\d{11}$/
    

    which will accept only 00-123-456-789 or 00123456789, but not allow only some dashes to be missing.

    Or, if you meant that you could have any number of digits and any number of single dashes between them, then you could use this:

    /^\d+(-\d+)*$/
    

提交回复
热议问题