Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for a 0.25 interval

Tags:

regex

My aim is to write a regular expression for a decimal number where a valid number is one of xx.0, xx.125, xx.25, xx.375, xx.5, xx.625, xx.75, xx.875 (i.e. measured in 1/8ths) The xx can be 0, 1 or 2 digits.

i have come up with the following regex:

^\d*\.?((25)|(50)|(5)|(75)|(0)|(00))?$

while this works for 0.25,0.5,0.75 it wont work for 0.225, 0.675 etc .

i assumed that the '?' would work in a case where there is preceding number as well.

Can someone point out my mistake

Edit : require the number to be a decimal !

Edit2 : i realized my mistake i was confused about the '?'. Thank you.

like image 329
Amit Vig Avatar asked Feb 16 '23 19:02

Amit Vig


2 Answers

I would add another \d* after the literal . check \.

^\d*\.?\d*((25)|(50)|(5)|(75)|(0)|(00))?$

like image 117
PuercoPop Avatar answered Feb 23 '23 08:02

PuercoPop


I think it would probably just be easier to multiply the decimal part by 8, but you don't consider digits that lead the last two decimals in the regex.

^\d{0,2}\.(00?|(1|6)?25|(3|8)?75|50?)$
like image 24
Explosion Pills Avatar answered Feb 23 '23 07:02

Explosion Pills