简体   繁体   中英

Regular expression to match a decimal value range

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.

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+(.\\d+)?$

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

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.

Using the bellow RegEx to parse strings for numbers. Can handle comma's and dots.

[^\\d.,](?<number>(\\d{1,3}(\\.\\d{3})*,\\d+|\\d{1,3}(,\\d{3})*\\.\\d+|\\d*[,\\.]\\d+|\\d+))[^\\d.,]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM