Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma Separated Numbers Regex

Tags:

regex

I am trying to validate a comma separated list for numbers 1-8.

i.e. 2,4,6,8,1 is valid input.

I tried [0-8,]* but it seems to accept 1234 as valid. It is not requiring a comma and it is letting me type in a number larger than 8. I am not sure why.

like image 323
Nick LaMarca Avatar asked May 18 '13 05:05

Nick LaMarca


1 Answers

[0-8,]* will match zero or more consecutive instances of 0 through 8 or ,, anywhere in your string. You want something more like this:

^[1-8](,[1-8])*$ 

^ matches the start of the string, and $ matches the end, ensuring that you're examining the entire string. It will match a single digit, plus zero or more instances of a comma followed by a digit after it.

like image 114
Cairnarvon Avatar answered Oct 05 '22 17:10

Cairnarvon