Regular expression: match 1 - 60 or all

I need help in REGEX in php (Symfony).

I want to match values ​​from 1 to 60 or all rows.

For the number, I use this: ^([1-5]?[0-9]|60) , but It matches 0 ... And I can’t combine “everything” now.

Could you help me? Thank you very much before

+4
source share
4 answers

You should be able to divide it into capabilities as follows:

 ^([1-9]|[1-5][0-9]|60|all)$ 

This gives you four possibilities:

  • [1-9] single digits.
  • [1-5][0-9] : all 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 are less useful for complex value checks (although in this case it is quite simple). 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 

sometimes it can be, although more detailed, also more readable and supported.

+12
source

It will fit all you need

 ^([1-9]|[1-5]\d|60|all)$ 
+4
source

You make [1-5] optional; rotate it like this: [1-5][0-9]? . You also need to cover a single bit [6-9] .

0
source

The problem is that you are missing parentheses, and you have to switch 60 and the rest, because otherwise it will only match 6 to 60:

 ^((60|([1-5]?[0-9]))|all) 
0
source

Source: https://habr.com/ru/post/1369485/


All Articles