Regex to accept numbers and/or number range separated by commas, but between range 1-4093

耗尽温柔 提交于 2020-06-09 07:10:30

问题


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


回答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



来源:https://stackoverflow.com/questions/42365968/regex-to-accept-numbers-and-or-number-range-separated-by-commas-but-between-ran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!