开发者

Understanding Regular Expression for Number Range

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 i am trying to create regular expressions for are as follows:

  1. Range 0-45, 0 decimal places
  2. Range 0-20, 2 decimal places
  3. Range 16-65, 0 decimal places
  4. Range 0-99, 2 decimal places
  5. Range 0-1500000, 0 decimal places
  6. Range 0-200, 1 decimal place

For 1 and 5 respectively, I have used

([0-9]|[0-9]\d|45)$  
([0-9]|[0-9]\d|1500000)$  

The first one I am having problems for is an age range of 16-65 (inclusive), where I want no decimal places. After a post on here (Regular expression to allow numbers between -90.0 and +90.0) I thought I could use the logic and get it sussed, but can't!

The expression I got to was:

(\d|([1-6][6-4]))|65  

Can someone please tell me where I'm misunderstanding this! And any help with the other examples above would be 开发者_如何学JAVAgratefuly received.


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).


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜