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

2

9

I need to write a regular expression for taking input like this

23,456,22,1,32767

i.e.

  1. No commas allowed at the start or end.
  2. Spaces may come before and/or start of comma for e.g. 23, 45,56 ,67 etc.
  3. Ranges of each number should be 0-32767.

Currently I am using regular expression like this [0-9]+(,[0-9]+)*.

This allows for numbers separated by commas only ( not allowing spaces at all), and it does not check for the range of number.

Combings answered 7/6, 2011 at 7:16 Comment(2)
You don't want to check the number range with regex, it will be relay unreadableSadie
codinghorror.com/blog/2008/06/…Wartow
I
16

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.

Ionopause answered 7/6, 2011 at 7:22 Comment(6)
+1, but you might want to add \s* around the comma to allow for spaces as Basmah asked.Stanislaus
"\s*" or " *"? The question seems very unclear on this point.Ionopause
Thanks Mark ! This was of help!Combings
Mark, would you please tell me the regex for th to write a regular expression for taking input like this 23,456,22,1,32767 i.e. 1.No commas allowed at the start or end. 2.Spaces may come before and/or start of comma for e.g. 23, 45,56 ,67 etc.e followingCombings
what should I change in this just to accept numbers separated by commas and no spaces in between?Zobias
how to make them non repeatingTanatanach
S
9

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.

Stanislaus answered 7/6, 2011 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.