Regex to match 2 digits, optional decimal, two digits
I've spent half an hour trying to get this, maybe someone can come up with it quickly.
I need a regular expression that will match one or two digits, followed by an optional decmial point, followed by one or two digits.
For example, it should match these strings in their entirety:
3
33
.3
.33
33.3
33.33
and NOT match anything with more than 2 digits before or after the decmial point.
Solution 1:
EDIT: Changed to fit other feedback.
I understood you to mean that if there is no decimal point, then there shouldn't be two more digits. So this should be it:
\d{0,2}(\.\d{1,2})?
That should do the trick in most implementations. If not, you can use:
[0-9]?[0-9]?(\.[0-9][0-9]?)?
And that should work on every implementation I've seen.
Solution 2:
(?<![\d.])(\d{1,2}|\d{0,2}\.\d{1,2})?(?![\d.])
Matches:
- Your examples
- 33.
Does not match:
- 333.33
- 33.333
Solution 3:
To build on Lee's answer, you need to anchor the expression to satisfy the requirement of not having more than 2 numbers before the decimal.
If each number is a separate string, you can use the string anchors:
^\d{0,2}(\.\d{1,2})?$
If each number is within a string, you can use the word anchors:
\b\d{0,2}(\.\d{1,2})?\b