Understanding Regular Expression for Number Range

前端 未结 2 1042
傲寒
傲寒 2020-12-19 13:31

I\'m trying to build up some regular expressions to validate some textbox controls. I have done some research and testing but cannot get this one working. Examples of what

相关标签:
2条回答
  • 2020-12-19 14:03

    Sorry to say this, but none of your regexes are going to work. Remember that regular expressions are designed to match textual data. While it's possible to use them to match numbers, it's not really the tool of choice.

    If you have to use a regex, you need to think of the possible textual representations of a number range.

    For your example 1, that would be:

    1. either a single digit
    2. or a digit between 1 and 3, followed by any digit
    3. or a 4, followed by a digit between 0 and 5.

    As a regex:

    ^(?:\d|[1-3]\d|4[0-5])$
    

    The ^ and $ anchors make sure that the entire string is evaluated; the (?:...) groups the alternation and "shields" it from the anchors.

    For your example 3:

    1. either a 1, followed by 6-9
    2. or a 2-5, followed by any digit
    3. or a 6, followed by 0-5

    As a regex:

    ^(?:1[6-9]|[2-5]\d|6[0-5])$
    

    For your example 5:

    1. 1-5 digits
    2. or a 1, followed by 0-4, followed by any four digits
    3. or 150000.

    As a regex:

    ^(?:\d{1,5}|1[0-4]\d{4}|150000)$
    

    And so on.

    Adding decimal places is not very difficult:

    • \.\d{2} works for exactly two decimal places
    • \.\d{1,3} for 1 to 3 decimal places
    • and (?:\.\d{1,2}) for 0 to 2 decimal places (and the dot is only allowed if at least one digit follows).
    0 讨论(0)
  • 2020-12-19 14:24

    The logic for 16 - 65 inclusive is 1 plus 6-9 OR 2-5 plus 0-9 OR 6 plus 0-5.

    Which I think would be 1[6-9]|[2-5][0-9]|6[0-5]

    0 讨论(0)
提交回复
热议问题