Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match 2 digits, optional decimal, two digits

Tags:

regex

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.

like image 985
Erix Avatar asked Jun 18 '09 18:06

Erix


People also ask

How do you write a decimal number in regex?

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.

Which regex matches one or more digits?

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.

How do I match a range of numbers in regex?

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.


1 Answers

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.

like image 143
Lee Avatar answered Sep 28 '22 05:09

Lee