Question

I have a quick question about regex for PHP.

My code:

^(\d{0,4}?)\.(?=(\d{1,2}))$

doesn't seem to work, where it's supposed to capture an optional group of up to 4 digits, then look ahead and conditionally capture a period based on if it captures a group of 1-2 digits. Does anyone know why this doesn't work?

Was it helpful?

Solution

That's not the right way to do it - nothing about your regex indicates that the . is optional.

Try:

^(\d{0,4})(?:\.(\d{1,2}))?$

This will match up to four digits, which may optionally be followed by a dot, then one or two digits. In any case, the two subpatterns will contain the groups of digits.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top