In an application I have the need to validate a string entered by the user.
One number
OR
a range (two numbers separated by a ‘-‘)
OR
a list of comma separated numbers and/or ranges
AND
any number must be between 1 and 999999.
A space is allowed before and after a comma and or ‘-‘.
I thought the following regular expression would do it.
(\d{1,6}\040?(,|-)?\040?){1,}
This matches the following (which is excellent). (\040 in the regular expression is the character for space).
- 00001
- 12
- 20,21,22
- 100-200
- 1,2-9,11-12
- 20, 21, 22
- 100 – 200
- 1, 2 – 9, 11 – 12
However, I also get a match on:
- !!!12
What am I missing here?
You need to anchor your regex
otherwise you will get a partial match on “!!!12”, it matches only on the last digits.
See it here on Regexr