2

What is the regular expression to allow for numbers between -90.0 and +90.0? The numbers in between can be floating or whole numbers.

Xaisoft
  • 45,655
  • 87
  • 279
  • 432

4 Answers4

17

I don't think you want to use a Regex for this. Use Double.Parse() (or Double.TryParse()) if your data is stored in a string, and then check the resulting value to ensure that it falls within the desired range. For example:

public bool IsInRange(string value)
{
   bool isInRange = false;

   double parsed = 0;
   if (Double.TryParse(value, out parsed))
   {
      // use >= and <= if you want the range to be from -90.0 to 90.0 inclusive
      isInRange = value > -90.0 && value < 90.0;
   }

   return isInRange;
}

If your value is already a double, then it's even easier -- no parsing required.

Donut
  • 110,061
  • 20
  • 134
  • 146
9

Not that you really want to use a Regex here (you should parse it, instead, and do the comparison on a numeric type - such as float, or double). But, you could do this:

-?(\d|([1-8][0-9])(\.\d)?)|(90(\.0)?)

This will match -90.0 to 90.0, inclusive. If you want it to be exclusive, drop the 90.0 clause.

  • negative (optional):
    -?

  • single digit
    OR double digit, 10-89
    \d|([1-8][0-9])
    PLUS decimal, 0-9 (optional):
    (\.\d)?

  • OR 90
    90
    PLUS decimal, 0 (optional):
    (\.0)?

If you want to support more decimal points, then change the 0-89.9 clause to:

  • Specific precision (seven, in this case) \d|([1-8][0-9])(\.\d{1,7})?
  • Infinite precision \d|([1-8][0-9])(\.\d+)?

Escape, if necessary

Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
1

"Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems."

This is a problem that would be better solved with a check. But, if you want a regex, you can have a regex.

-?0*((90(\.0*)?)|([1-8]?\d(\.\d*)?))

will work, I think. Match an optional '-', followed by any number of zeros, followed by either 90 with any number of zeros, or a number that consists of an optional tens digit between 1 and 8, followed by a ones digit, followed by a optional decimal and decimal places. But you see why using a regex for this is so messy. Check the bounds as a numbers, not a series of numerals.

Theo Belaire
  • 2,980
  • 2
  • 22
  • 33
0

A straightforward regex for +/- option sign of a 90.0 range with optional float of 1 decimal place would be :

[-+]?90(?:\.0?)?|[-+]?(?:\d|[1-8]\d)(?:\.\d?)?

Expanded

   #   [-+]  90.0

   [-+]? 90
   (?: \. 0? )?
|  
   #    [-+]  89.9  to   0.0
   #           0.0  to  89.9

   [-+]? 
   (?:
        \d 
     |  [1-8] \d 
   )
   (?: \. \d? )?