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.

2 answers

  • answered 2018-07-12 07:20 Richard

    Firstly [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[1]).

    So something like:

    ^\d+(-\d+)?$
    

    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
    

    [1] it, depending on your specific regex engine, may match non-ASCII digits from Unicode, but you'll need to check your documentation for that.

  • answered 2018-07-12 07:24 Bhavesh Vavadiya

    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

    ^(([0-9]+)|([0-9]+[-][0-9]+))$