Comma Separated Numbers Regex

Regex

Regex Problem Overview


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.

Regex Solutions


Solution 1 - Regex

[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.

Solution 2 - Regex

/^\d+(,\d+)*$/
  • for at least one digit, otherwise you will accept 1,,,,,4

Solution 3 - Regex

[0-9]+(,[0-9]+)+

This works better for me for comma separated numbers in general, like: 1,234,933

Solution 4 - Regex

You can try with this Regex:

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

Solution 5 - Regex

If you are using python and looking to find out all possible matching strings like XX,XX,XXX or X,XX,XXX or 12,000, 1,20,000 using regex

string = "I spent 1,20,000 on new project "
re.findall(r'(\b[1-8]*(,[0-9]*[0-9])+\b)', string, re.IGNORECASE)

> Result will be ---> [('1,20,000', ',000')]

Solution 6 - Regex

You need a number + comma combination that can repeat:

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

If you don't want remembering parentheses add ?: to the parens, like so:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick LaMarcaView Question on Stackoverflow
Solution 1 - RegexCairnarvonView Answer on Stackoverflow
Solution 2 - RegexAnkit VishwakarmaView Answer on Stackoverflow
Solution 3 - RegexJimmyView Answer on Stackoverflow
Solution 4 - RegexSantosh PandaView Answer on Stackoverflow
Solution 5 - Regexkiran beethojuView Answer on Stackoverflow
Solution 6 - Regexquux00View Answer on Stackoverflow