views:

1442

answers:

4

Is there an easy way to take a dynamic decimal value and create a validation regular expression that can handle this?

For example, I know that /1[0-9]{1}[0-9]{1}/ should match anything from 100-199, so what would be the best way to programmatically create a similar structure given any decimal number?

I was thinking that I could just loop through each digit and build one from there, but I have no idea how I would go about that.

+1  A: 

Ranges are difficult to handle correctly with regular expressions. REs are a tool for text-based analysis or pattern matching, not semantic analysis. The best that you can probably do safely is to recognize a string that is a number with a certain number of digits. You can build REs for the maximum or minimum number of digits for a range using a base 10 logarithm. For example, the match a number between a and b where b > a, construct the RE by:

re = "[1-9][0-9]{"
re += str(log10(a)-1)
re += "-"
re += str(log10(b)-1)
re += "}"

Note: the example is in no particular programming language. Sorry, C# not really spoken here.

There are some boundary point issues, but the basic idea is to construct an RE like [1-9][0-9]{1} for anything between 100 and 999 and then if the string matches the expression, convert to an integer and do the range analysis in value space instead of lexical space.

With all of that said... I would go with Mehrdad's solution and use something provided by the language like decimal.TryParse and then range check the result.

D.Shawley
A: 

^[-]?\d+(.\d+)?$

will validate a number with an optional decimal point and / or minus sign at the front

Tekdream
yes, I understand that, but that does not deal with the ranges.
Ed Woodcock
I would reconsider using a regular expression for that and just use a programming language (C#, javascript, whatever). A regex isn't really the right tool for the job here - unless there is some reason you are absolutely forced to use a regex.
Tekdream
A: 

No, is the simple answer. Generating the regex that will work correctly would be more complicated than doing the following:

  1. Decimal regex (find the decimal numbers in a string). "^\$?[+-]?[\d,]*(\.\d*)?$"
  2. Convert result to decimal and compare to your range. (decimal.TryParse)

This depends on where and what you want to parse.

Charles Beattie
In this case use a custom validator as Andrew Hare suggests.
Charles Beattie
This is working for me in validation controls
Lalit