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.
A regular expression for a decimal number needs to checks for one or more numeric characters (0-9) at the start of the string, followed by an optional period, and then followed by zero or more numeric characters (0-9). This should all be followed by an optional plus or minus sign.
Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. Something like ^[2-9][1-6]$ matches 21 or even 96! Any help would be appreciated.
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.
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