0

Is there a more efficient way to check integers in the intervall from 0 to 250?

Regular Expression:

^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|250)$

Or what about an intervall from 0 to 20'000, 0 to 100'000, etc.?

phonophunk
  • 67
  • 8
  • 2
    Nope, I don't think there is easier way of doing that using regex. – MarcinJuraszek Jun 02 '14 at 16:58
  • No more efficient way to do it (other than slightly optimizing it like @TimPietzcker did), and the expression will get exponentially larger as you go. [Check an answer of mine on a similar question..](http://stackoverflow.com/questions/23637637/regex-for-checking-if-number-is-less-or-greater-than/23637810#23637810) – Sam Jun 02 '14 at 17:02
  • **Regular expressions are for matching patterns, not checking numeric values.** Find a likely string with a regex like `/^\d+$/`, then check its numeric value in whatever your host language is (PHP, whatever). – Andy Lester Jun 02 '14 at 17:05
  • Okay, damn. The reason, I wanted to use reg ex is, that I want to prevent user inputs (in C#/ WPF) of letters and special characters. Any user should only be allowed to enter integers in the range from 0 to 250, resp. 0 to 20000... – phonophunk Jun 02 '14 at 17:08
  • By the way I use in WPF textboxes, that allow by default strings, that should be validated... – phonophunk Jun 02 '14 at 17:16

1 Answers1

1

Not really; you can shorten it a tiny bit:

^([1-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|250)$

But regexes are not good for number ranges, especially arbitrary ranges.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561