Creating a regex to match numbers or a range of number
I've been looking at regex help pages but cant seem to find/understand a solution.
My problem is: I want a regex that allows either specifically a number or a range of numbers that will be integrated in a code for data input validation. For example one can only input either "12" or "12-50" with that exact same format, no extra dashes or anything.
The solution I created for the ex."12-50" is
[0-9][-][0-9] and works perfectly fine. However I can't integrate the above regex with one that will allow that format and also the format of just a single number.
I tried using the OR operator,
[0-9]|[0-9][-][0-9], however it doesn't seem to work perfectly as I can input "incorrect formats" such as "12-","123---" etc.
[0-9][-][0-9]is not matching the whole of "12-50", just the "2-5" substring. And that explains your false positives: in each case the regex is matching a substring.
Therefore you need to start by matching the whole string:
Also, you want sequences of digits rather than single digits so say that:
\d+matches one or more digits ('\d' matches a digit).
So something like:
should work. Expanding this
^ Start of string \d+ One or more digits ( Start of group -\d+ Dash followed by one or more digits ) End of group ? Preceding element – the group – is optional $ End of string
 it, depending on your specific regex engine, may match non-ASCII digits from Unicode, but you'll need to check your documentation for that.
As you want exact match pattern, you need to use start and ending indicator.
^ : Indicate starting
$ : Indicate ending
| : To give more than one regex using or condition
'+' : To find atleast one accurance