-2

I need a regex to validate VLAN string entered by user. The string should allow numbers or ranges, separated by comma. The numbers must be between 1 and 4093.

Below samples are allowed:

1,
1,2,3,4
1-10, 
1-4093
4000

I tried below :

^0*([1-9]|[1-8][0-9]|9[0-9]|[1-8][0-9]{2}|9[0-8][0-9]|99[0-9]|[1-3][0-9]{3}|40[0-8][0-9]|409[0-3])$  

Need to enhance for comma separated and ranges

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
Rinky
  • 31
  • 1
  • 6
  • 1
    Pure code-writing requests are off-topic on Stack Overflow -- we expect questions here to relate to *specific* programming problems -- but we will happily help you write it yourself! Tell us [what you've tried](http://stackoverflow.com/help/how-to-ask), and where you are stuck. This will also help us answer your question better. – Thomas Ayoub Feb 21 '17 at 11:27
  • Can you show us what you tried and what the result was? – SaggingRufus Feb 21 '17 at 11:28

2 Answers2

1

To match a number from 1 to 4093 one can use:

(?:[1-9]\d{0,2}|[1-3]\d{3}|40(?:[0-8]\d|9[0-3]))

That we'll call N. Now the repetition part:

^(N)(?:[,-] *(N)?)*$

which gives:

^(?:[1-9]\d{0,2}|[1-3]\d{3}|40(?:[0-8]\d|9[0-3]))(?:[,-] *(?:[1-9]\d{0,2}|[1-3]\d{3}|40(?:[0-8]\d|9[0-3]))?)*$

Live demo

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
  • 1
    @Rinky please accept the answer as it helps others to identify that the problem is solved and proper credits goes to the person who answered – Abdul Hameed Feb 22 '17 at 04:46
0

regex for vlan id range 1-4093

(40(?:[0-8]\d|9[0-3])|[1-3]\d{2,3}|\d{2,3}|[1-9])