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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top