lmh lmh - 4 months ago 21
PHP Question

what is the difference between ^([1-9]\d*|0)$ and ^[1-9]\d*|0$

What's the difference between these two regular expressions:

1.

^([1-9]\d*|0)$


2.
^[1-9]\d*|0$


The first expression works for
6.1
and
6
. The second expression only works for
6
. Why is this?

Answer

You must be confused because you expected the | to have higher precedence than the ^ and $, but it actually has lower precedence.

^[1-9]\d*|0$ is equivalent to (^[1-9]\d*)|(0$) not ^([1-9]\d*|0)$.

Comments