Reputation: 101
I want to have a regexp to validate DECIMAL numbers:
The valid DECIMAL numbers are :
+123
123
-123
+123.0000
+123,123.999
.0234
+1123,233,34
invalid DECIMAL numbers are :
+1233+
-1233_
+12.233.33
Is there any one who can help on this
Upvotes: 1
Views: 407
Reputation: 17194
This works for all:
+123
123
-123
+123.0000
+123,123.999
.0234
+1123,233,34
check the demo:
^[+\-]?(\d+(,?\d)*(\.\d*)?|\.\d+)$
Upvotes: 1
Reputation: 6566
I think this is about the simplest you can get:
^[+-]?\d*\.?\d+$
Digits are always required after the decimal point. Taking advantage of this fact simplifies the problem.
Update: At first I didn't notice that you also need to handle commas. Here is a simple version that allows commas to the left of the decimal point. Each comma must have at least one digit before and after it, but other than that no rule is enforced (which seems to be the point of your example data). Actually, it requires two digits after the final comma.
^[+-]?(\d+(,\d)?)*\.?\d+$
Upvotes: 1
Reputation: 852
Depends on your regular expression support.
^([-+])?(\d+)?(\.\d+)?$
Optional + or -, numeric, optional ',' followed by more numerics. Will also match the empty string unfortunately.
Upvotes: 1
Reputation: 10786
This is better:
^[+\-]?\d+(,\d{3})*(\.\d*)?$
Plus or minus, optionally, followed by any number of digits, followed optionally by any number of ,123
sections, followed optionally by a decimal and some more digits, this will handle anything except numbers with a leading decimal.
^[+\-]?(\d+(,\d{3})*(\.\d*)?|\.\d+)$
Adding that other option allows numbers with a leading decimal, which MUST be followed by digits.
Upvotes: 2