I need some help on a REGEX in php (Symfony).
I want to matc开发者_开发问答h values 1 to 60 or string all.
For number I've use this : ^([1-5]?[0-9]|60)
but It match 0 ... And I don't now how can match "all".
Can you help me ? Many thanks before
You should be able to divide it into possibilities as follows:
^([1-9]|[1-5][0-9]|60|all)$
This gives you four possibilities:
[1-9]
the single-digit values.[1-5][0-9]
: everything from ten to fifty-nine.60
: sixty.all
: your "all" option.
But keep in mind that regular expressions are not always the answer to every question.
Sometimes they're less useful for complicated value checks (though, in this case, it's a fairly simple one). Something like the following (pseudo-code):
def isAllOrOneThruSixty(str):
if str == "all":
return OK
if str.matches ("[0-9]+"):
val = str.convertToInt()
if val >= 1 and val <= 60:
return OK
return BAD
can sometimes be, while more verbose, also more readable and maintainable.
This will match all you need
^([1-9]|[1-5]\d|60|all)$
You are making the [1-5]
optional; turn it around, like so: [1-5][0-9]?
. Also you need to cover the single-digit [6-9]
.
The problem is that you are missing some parenthesis and you should switch the 60 and the rest, because otherwise it will only match the 6 in 60:
^((60|([1-5]?[0-9]))|all)
精彩评论