Reputation: 13412
I think it only happens when I write a regex. I have a simple regex to validate a set of pagination numbers, that later will be submitted to database, like 5
, 10
, 25
, 50
, 100
, 250
example:
/all|5|10|25|50|100|250/
When I perform a test, my regex above cuts 0
only from numbers 50, 100 and 250 but not from 10
!!?
Online example:
http://viper-7.com/IbKFKw
What am I doing wrong here? What am I really missing this time?
Upvotes: 3
Views: 117
Reputation: 44279
The alternatives are tried from left to right, so matching 5
takes precedence over 50
. But there's no 1
to cut off the 0
from 10
. You can simply reorder them:
/all|250|100|50|25|10|5/
Alternatively, add the 0
optionally to the relevant alternatives (and since ?
is greedy, the 0
will be matched if present):
/all|50?|100?|250?/
or
/all|(?:5|10|25)0?/
If this is not for matching but for validation (i.e. checking against the entire string), then go with Jerry's suggestion and use anchors to make sure that there are no undesired characters around your number:
/^(?:all|5|10|25|50|100|250)$/
(Of course inside (?:...)
you could also use any of my above patterns, but now precedence is irrelevant because incomplete matches are disallowed.)
Upvotes: 7
Reputation: 71568
This is because in the string 50
, the regex first matches 5
, which is valid. In the string 250
, the regex first matches 25
, which is valid and ends here.
You might try adding anchors:
/^(?:all|5|10|25|50|100|250)$/
This forces the regex to match the whole string, and hence, return the correct match you are looking for.
Upvotes: 10