Reputation: 2931
I need to validate a string that can have the following format:
0000000000-0000
1001
1001-1
Possible format that should validate
XXXXXXXXXX-XXXX
XXXX
XXXX-X
Only digits are required in the string and the - sign is optional. At least 4 digits (up to 10) then optional - sign then a max of 4 more digits (also optional).
I tried \d{4,}-?\d*
but as shown here it's matching 1232-test
and it shouldn't be. The whole string must be numeric and optional -
sign, nothing else.
All the above should pass the regex but nothing else. I could try all day long to come up with something but since I never dig into regex I turn to you guys.
Upvotes: 0
Views: 36
Reputation:
Try this ^\d{4,10}(?:-\d{1,4})?$
https://regex101.com/r/00GCtH/1
Formatted
^ # Begin of string
\d{4,10} # Required 4 to 10 digits
(?: # Optional dash and 1 to 4 digits
- \d{1,4}
)?
$ # End of string
Upvotes: 2
Reputation: 25351
Your current regex is OK, just add the beginning and end of the line to it:
^\d{4,}-?\d*$
However, if you want to restrict it to your upper limits (up to 10, followed by up to 4) then add them:
^\d{4,10}-?\d{0,4}$
Upvotes: 0