T
T
Thehavoc2020-03-06 09:23:30
Regular Expressions
Thehavoc, 2020-03-06 09:23:30

How to limit the range of two digit numbers in a non-trivial regular expression?

There is a regular expression that checks for a string of user input.
Each number has a limit from 1 to 16.
A string can be with one or more subranges of numbers from 1 to 16, for example:
"1,3,5,7-11,15"
"1-3,5-8,12,13 -16"
"1-16"
Wrote a regular expression that allows numbers from 1 to 99:


^([1-9]{0,2}((-[1-9]{0,}){0,2})(,([1-9]{0,2}((-[1- 9]{0,2}){0,1}))){0,})$

but how to limit numbers from 1 to 16, I can’t catch up.
Maybe there are ready-made examples applicable for this task?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Pankov, 2020-03-06
@Thehavoc

You can describe a number from 1-16 with a regular expression like this: (1[0-6])|([1-9])
But regexps are not meant for conditional filtering on expressions.
Usually they define only the syntax and divide the text into groups, which then need to be converted to types and checked.
If you still feel like it, use my version of describing the number 1-16, but tomorrow you will need to determine the parity, and the day after tomorrow you will need the right border of the interval to be twice the left ... You need to stop somewhere and where exactly - it's up to you.
Here it is in your case:

^((1[0-6]|[1-9])(-(1[0-6]|[1-9]))?)(,((1[0-6]|[1-9])(-(1[0-6]|[1-9]))?))*$

You can even test

A
AUser0, 2020-03-06
@AUser0

^(1[0-6]|[1-9])(-(1[0-6]|[1-9]))?(,(1[0-6]|[1-9])(-(1[0-6]|[1-9]))?)*$

But if the results of the capturing group from the RegEx are then used for text processing - then this line will not work, it will only give the first and last numbers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question