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 for validation. Ideally, I need a common regex, which will work for both.
If you want to match the entire line, than something like this should do:
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
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[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 logicalOR– either part before it matches or the part after itThus 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.