I need a regular expression for 6 digit number with optional 2 decimal digit Allowed values:
.1 .11 0.11 10. 10.1 10.12 00.00 0.0 00.00
123456 12345 1234 123 12 1 0 0. 123. 123.55 123456.
The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.
\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).
Regex should be: ^\d{0,6}(\.\d{0,2})?$
(It passed all of your samples)
Update:
To avoid empty string and single dot, regex is ^(?!\.?$)\d{0,6}(\.\d{0,2})?$
. The expression adds a negative lookahead ?!\.?$
, which excludes 0 or 1 dot.
I added a unit test on Fiddle.
Let's break it into four regexes. At least one of these four must match.
# decimal, 1-2 digits
\.\d{1,2}
# 1-4 digits, optional decimal, 0-2 digits
\d{1,4}\.?\d{0,2}
# 5 digits, optional decimal, optional digit
\d{5}\.?\d?
# 6 digits, optional decimal
\d{6}\.?
Which can then be combined into a single regex with the alternation operator (|
):
(\.\d{1,2}|\d{1,4}\.?\d{0,2}|\d{5}\.?\d?|\d{6}\.?)
Then add a caret (^
) and stick ($
) to match the beginning and end of the string.
^(\.\d{1,2}|\d{1,4}\.?\d{0,2}|\d{5}\.?\d?|\d{6}\.?)$
This doesn't scale very well (e.g. if you wanted to match 100 digits with up to 20 after the decimal point) but it works and it's relatively easy to understand.
If you don't have to use a regex, there are easier ways to solve this problem. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With