Reputation: 3278
I have this javascript Regex (3 decimal places wiht a single dot)
^\d+(\.\d{1,3})?$
I want to also match on an empty string ""
which i believe is
^$
How can I combine these into 1 regex
These should be the passing tests
"" //empty string
1
1.
1.0
1.00
1.000
123456789
0
.0
.00
.000
I hope I have covered all of them.
Upvotes: 1
Views: 2309
Reputation: 20504
The digit period case was a difficult one, that my original answer missed. This answer is simpler than the others, covers all cases, and doesn't have any false matches.
Expression
^((\d+\.?|\.(?=\d))?\d{0,3})$
Upvotes: 1
Reputation: 7575
Not including the empty space, your current expression doesn't seem to pass your requirements.
^\d*\.?\d{0,3}$
Optional leading digits, optional point, up to three more digits before the end.
EDIT: @Guffa noticed that my original solution would also match simply a dot, "."
^\d*((\d\.)|(\.\d))?\d{0,3}$
This version replaces the \.?
check with a check for a digit followed by a dot, or a dot followed by a digit, or neither.
Upvotes: 3
Reputation: 700342
Make an expression with three different cases:
This will pass all your tests, and also the string "."
will not pass:
^(\d*|\d+\.\d{0,3}|\d*\.\d{1,3})$
Demo: http://jsfiddle.net/Guffa/9pnwk/
Upvotes: 2
Reputation: 7119
I would rather go for a ==="" or your regex comparison, just for performance's sake
Upvotes: 1