Skip to content Skip to sidebar Skip to footer

Regular Expression For Csv Numbers From 1 To 1000

I need a regex that can match a string of numbers from 1 to 1000 separated by commas. eg : 12,56,100,190,900,1000 I am using javascript on the front end and php on the back end f

Solution 1:

Numbers in the range 1-1000, separated commas, is matched by

(?<=,|^)([1-9][0-9]{0,2}|1000)(?=,|$)

Solution 2:

If you want to match the entire line, than something like this should do:

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

Depending on your requirements, you may also want to allow whitespace in the beginning, end, and/or after commas.

This will allow whitespace in the beginning: ^\s*([1-9][0-9]{0,2}|1000)(,([1-9][0-9]{0,2}|1000))*$

This will allow whitespace at the end: ^([1-9][0-9]{0,2}|1000)(,([1-9][0-9]{0,2}|1000))*\s*$

This will allow whitespaces after commas: ^([1-9][0-9]{0,2}|1000)(,\s*([1-9][0-9]{0,2}|1000))*$

Combine these to your liking.

EDIT 2: If you want to allow a comma in the binning or at the end, then your regex becomes

^,?([1-9][0-9]{0,2}|1000)(,\s*([1-9][0-9]{0,2}|1000))*,?$

Here, ,? means that you can have 0 or 1 comma.

EDIT: explanation, as requested:

  • ^ in the beginning and $ at the end are start/end of input marks - they ensure that we test the entire input
  • Parentheses work just as you would expect them
  • [1-9] matches a digit 1 through 9, similarly [0-9] matches a digit 0 through 9
  • {0,2} indicates that the previous part (in our case [0-9]) is present between 0 and 2 times
  • | is a logical OR - either part before it matches or the part after it

Thus in the first set of parentheses we match digit 1 to 9 followed by 0, 1 or 2 digits 0 to 9 - this gives us numbers between 1 and 999 - or we match 1000.

Then we match a comma followed by the same block as described above - and this lot is matched 0 or more times - as indicated by * character after the parentheses.

Post a Comment for "Regular Expression For Csv Numbers From 1 To 1000"