REGEX To accept numbers separated by commas, but number range is 0-32767

自闭症网瘾萝莉.ら 提交于 2019-12-04 03:48:39

It's probably wise to do it in two steps. First check that the range is 0-99999:

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

Then parse the string to a list of integers using a general purpose programming language and check that x <= 32767 for each integer x.

You can validate a number range with a regex, but since you need to look at the textual representation of numbers, the regex will be hard to read:

0*(?:3276[0-7]|327[0-5][0-9]|32[0-6][0-9]{2}|3[01][0-9]{3}|[12][0-9]{4}|[1-9][0-9]{1,3}|[0-9])

matches an integer between 0 and 32767, with optional leading zeroes.

So your entire regex would be

^0*(?:3276[0-7]|327[0-5][0-9]|32[0-6][0-9]{2}|3[01][0-9]{3}|[12][0-9]{4}|[1-9][0-9]{1,3}|[0-9])(?: *, *0*(?:3276[0-7]|327[0-5][0-9]|32[0-6][0-9]{2}|3[01][0-9]{3}|[12][0-9]{4}|[1-9][0-9]{1,3}|[0-9]))*$

Now imagine you inherit that regex from a co-worker who has left your company years ago...Have fun :)

Therefore, take Mark's advice.

This answer is intended purely for educational purposes and does not constitute a recommendation to use a regex in this case.

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