Search code examples
regexregex-lookarounds

Regex to validate a number


I am trying to resolve an issue with regex,within a text box i wish to have a number which is a 3 digit number,wherein the 1st digit (i.e the number in hundreds position) should be greater than or equal to 5, and the following number in the tens place should be greater than the number in hundreds place (which is 5 in our case) and the number in units place should be greater than the number in tens place

e.g. valid strings : 567,789,689,589 invalid string : 123,556,896,765


Solution

  • Note:

    Numerical comparison should generally be done through ordinary code not regex. Both for efficiency and code readability reasons.

    Here is the regex: [5-7][6-8](?<=5[6-8]|6[78]|78)[7-9](?<=6[7-9]|7[89]|89)

    A demo: https://regex101.com/r/nQfsE9/3

    A breakdown:

    \b                    # Ensures starting of a number
    [5-7]                 # First digit can't be higher than 7
    [6-8]                 # Second digit can't be higher than 8
    (?<=5[6-8]|6[78]|78)  # Lookback checks second digit larger than third
    [7-9]                 # Last digit must be at least 7
    (?<=6[7-9]|7[89]|89)  # Lookback checks second digit larger than third
    \b                    # Ensures ending of a number