In regular expression or operator between 2 group is not working

I am trying to create JavaScript regex expression of range 0 to 8759.59

I have created 2 regex expression: Below is my expression for this:

Regex1

^([0-9]|[1-8][0-9]|9[0-9]|[1-8][0-9]{2}|9[0-8][0-9]|99[0-9]|[1-7][0-9]{3}|8[0-6][0-9]{2}|87[0-5][0-9]|8759)(\.([0-9]|[1-4][0-9]|5[0-9]))?$

And another expression for range 0 to 8758.99 not accept 8760, Below is the expression for this:

Regex2

^([0-9]|[1-8][0-9]|9[0-9]|[1-8][0-9]{2}|9[0-8][0-9]|99[0-9]|[1-7][0-9]{3}|8[0-6][0-9]{2}|87[0-5][0-9]|8758)(\.\d{1,2})?$

Now when I try to put or operator between Regex2 and Regex1 then it not working as expectation.

I want it should accept value in range of 0-8759.59

3 answers

  • answered 2018-04-17 04:54 Rizwan M.Tuman

    Update As Per OP's Comment: ( This will match anything less than 8759.60 )

    ^8759(\.[0-5]\d?)?$|^(87[0-5][0-8]|8[0-6]\d{2}|[0-7]\d{3}|\d{1,3})(\.\d\d?)?$
    

    Updated Code Snippet

        const regex = /^(87[0-5]\d|8[0-6]\d{2}|[0-7]\d{3}|\d{1,3})(\.[0-5]\d?)?$/;
        console.log(regex.test(`0`));
        console.log(regex.test(`8759.59`));
        console.log(regex.test(`8759.60`));
        console.log(regex.test(`10.59`));
        console.log(regex.test(`10.60`));
        console.log(regex.test(`8759`));
        console.log(regex.test(`876`));
        console.log(regex.test(`8761`));
        console.log(regex.test(`123.1`));

    Explanation:

    • ^ start of string
    • (87[0-5]\d|8[0-6]\d{2}|[0-7]\d{3}|\d{1,3}) 4 alternatives where -
    • 87[0-5]\d 87 followed by anything between 0-5 and then any digit OR

      8[0-6]\d{2} 8 followed by anything between 0-6 and the any two digit OR

      [0-7]\d{3} 0-7 followed by any 3 digits

      OR

    • \d{1,3} any 1 to 3 digits

  • answered 2018-04-17 04:54 Thm Lee

    You can try this,

    ^8759(?:\.[0-5]\d?)?$|^(?:(?:(?:|[1-9]|[1-9]\d|[1-7]\d{2})\d|8[0-7][0-5][0-8])(?:\.\d{1,2})?)$
    

    Demo

    Edited because above regex missed the point which 8[0-7][0-5][0-8] does not accept legitimate inputs, 8199, 8369, etc

    ^8759(?:\.[0-5]\d?)?$|^(?:(?:(?:|[1-9]|[1-9]\d|[1-7]\d{2})\d|8(?:[0-6]\d{2}|7(?:[0-4]\d|5[0-8])))(?:\.\d{1,2})?)$
    

    Demo

    Changed part from 8[0-7][0-5][0-8]

    8(?:[0-6]\d{2}|7(?:[0-4]\d|5[0-8]))
    

  • answered 2018-04-17 04:54 axiac

    The regular expressions are not the tool to verify if a number belongs to a certain range.
    The are a good tool to check if a string is the text representation of a number, so let's use them for this purpose and let the comparison operators handle the range check:

    function validateNumber(input, min, max)
    {
        const re = /^\d+(\.\d*)?$/
    
        if (re.exec(input)) {
           let nb = parseFloat(input)
           return min <= nb && nb <= max
        } else {
           return false
        }
    }
    
    console.log(validateNumber('8759.60', 0, 8759.59))