Reputation: 5670
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 for 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
Upvotes: 0
Views: 870
Reputation: 27913
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.
Upvotes: 1
Reputation: 208425
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.
Upvotes: 2
Reputation: 60190
The regex seems to be fine, however the processing afterwards (DB or whatever) may not accept this format.
Upvotes: 1
Reputation: 8182
http://www.regular-expressions.info/floatingpoint.html
[-+]?[0-9]*\.?[0-9]*
Actually pyroscope got it right with a + at the end instead of a *
Upvotes: 1