Regular Expression for number and dash

后端 未结 7 574
醉话见心
醉话见心 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:29

    If I understand you correctly, you wish your regex to stand for strings which consist of a number group followed (optionally) by additional number groups with a - separator.

    \d+      # represents a number group
    (-\d+)*  # represents 0 or more additional number groups beginning with "-"
    

    So, together with the necessary beginning and end of line assertions, together we have:

    ^\d+(-\d+)*$
    
    0 讨论(0)
  • 2020-12-15 23:38

    From what have you provided us, this regex ^-?(\d+-?)+$ matches this

    -00-123-456-789-
    -00123456789-
    00-123-456-789-
    00123456789
    

    but doesn't match this:

    00-123--457-789
    

    Breakdown:

    • the string can start with a dash (^-?)
    • it has some digits followed by an optional dash (\d+-?)
    • the last group can be repeated one or more times ((\d+-?)+)
    • the string ends ($)
    0 讨论(0)
  • 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+)*$/
    
    0 讨论(0)
  • 2020-12-15 23:47

    If you only want to accept ##-###-###-### or ###########, then what you need is something like:

    /^(([\d+]{2}\-)([\d]{3}\-){2}([\d]{3})|[\d]{11})$/
    
    0 讨论(0)
  • Try something like this

    /^(\d+-?)+\d+$/
    
    0 讨论(0)
  • 2020-12-15 23:51

    The following answer will be used to match

    00-123-456-789 or 00 123 456 789

    /^[\d]{2}[-\s]?[\d]{3}[-\s]?[\d]{3}[-\s]?[\d]{3}$/

    If you want only to match hyphen(-) or without hyphen(-)

    Then it will do

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

    0 讨论(0)
提交回复
热议问题