Range in Regular Expressions

While searching for ranges in regular expressions I found this page: http://utilitymill.com/utility/Regex_For_Range/42 The page generates regular expressions for ranges and works really nice. You want for example a regex for the range 12 to 389 and the page generates this for you: 


Unfortunately negative values are not allowed. But I needed to have an regex for the range between -128 and 127. If you also need something like this to define types like short or byte, there is a nice trick.

  1. generate the regex from 0 to 128: ^([0-9]{1,2}|1[01][0-9]|12[0-8])$
  2. add an optional – in the beginning: ^[-]?([0-9]{1,2}|1[01][0-9]|12[0-8])$
  3. exclude 128: ^(?!128)[-]?([0-9]{1,2}|1[01][0-9]|12[0-8])$

And there you have it, a range regex for values from -128 to 127.