Numeric Regular Expression for "optional sign, optional digits, optional dot, one or more digits"
I've got a regular expression that I'm using for validating a decimal type number in .NET.
Current Regular Expression
[-+]?[0-9]*\.?[0-9]+
(EDIT - My problem was due to the Regular Expression [-+]?[0-9]*\.?[0-9]
: I was missing the +
at the end)
The SQL database I'm working with has the number defined as numeric(28,12), so I suppose I need to validate anything in that range, although by business logic enforces a value of 0 to 9,999.99.
So, while any data I put in using my validation will work fo开发者_开发知识库r the business rules defined, I have to account for data already in the database, as it's fed by another system.
I need all those numbers to validate:
.5
0.5
450.000000000000
.450
The regex as you have it now should work fine. Here is a walk through of each portion of the regex:
[-+]? # matches '-' or '+', optional
[0-9]* # matches zero or more digits, as many as possible
\.? # matches a '.', optional
[0-9]+ # matches one or more digits, as many as possible
For ".5" the first two portions are missing, but that would not fail the match. Not sure why you are having troubles but it could be with the .NET code, post it and we can try to help.
You may want to try escaping the "-" in your first character class ([\-+]
), this shouldn't be necessary since the "-" is the first character, but when "-" is in a character class it usually specifies a range.
[-+]?[0-9]*\.?[0-9]+
Escaping issue with the ".".
http://www.regular-expressions.info/floatingpoint.html
[-+]?[0-9]*\.?[0-9]*
Actually pyroscope got it right with a + at the end instead of a *
The regex seems to be fine, however the processing afterwards (DB or whatever) may not accept this format.
Use \d
to represent digits. This takes into account decimal numbers without leading numbers.
^[-+]?(?:\d+(?:\.\d+)?|\.\d+)$
Also, the noncapturing groups (?:regex)
make it perform better since the engine must do less capturing work.
精彩评论