Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex : Match 1 to 60 or all

Tags:

string

regex

php

I need some help on a REGEX in php (Symfony).

I want to match 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

like image 432
prcaen Avatar asked Dec 03 '22 07:12

prcaen


2 Answers

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.

like image 71
paxdiablo Avatar answered Dec 23 '22 18:12

paxdiablo


This will match all you need

^([1-9]|[1-5]\d|60|all)$
like image 29
zerkms Avatar answered Dec 23 '22 18:12

zerkms