Currently I write the regex like this: /^([\\d+]*-)+([\\d]*-)+([\\d])*$/
I want the result follow this pattern 00-123-456-789
or 0012
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+)*$
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:
^-?
)\d+-?
)(\d+-?)+
)$
)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+)*$/
If you only want to accept ##-###-###-### or ###########, then what you need is something like:
/^(([\d+]{2}\-)([\d]{3}\-){2}([\d]{3})|[\d]{11})$/
Try something like this
/^(\d+-?)+\d+$/
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}$/