57

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.

SethO
  • 2,703
  • 5
  • 28
  • 38
Nick LaMarca
  • 8,076
  • 31
  • 93
  • 152

6 Answers6

69

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

Cairnarvon
  • 25,981
  • 9
  • 51
  • 65
  • 1
    it will break if I will try to check against the values 1234, 1345 , 4455 – Ankit Vishwakarma Mar 10 '18 at 05:22
  • 13
    In a more general case, [`^[0-9]+(,[0-9]+)*$`](https://regex101.com/r/xbxBV7/1) (since the title - *Comma Separated Numbers Regex* - sounds broader than what OP describes in the question body). – Wiktor Stribiżew Jul 13 '18 at 10:15
  • 1
    @WiktorStribiżew in an even more general case, you could use `^\d+(,\d+)*$` because `\d` means "digit", or `[0-9]` in base 10 – chharvey Nov 30 '18 at 16:46
  • @chharvey `\d` is not supported by some regex engines, like POSIX, so `[0-9]` is safer in the context of a question that has only one, `regex`, tag. This is why I did not use a non-capturing group in my answer. – Wiktor Stribiżew Nov 30 '18 at 17:21
32
/^\d+(,\d+)*$/
  • for at least one digit, otherwise you will accept 1,,,,,4
als
  • 13
  • 4
Ankit Vishwakarma
  • 1,573
  • 16
  • 13
  • 1
    OP is trying to validate a comma-separated list of digits from 0 through 8 inclusive, not a comma-separated list of any number of digits. – Paul Jul 09 '18 at 14:55
  • 13
    But it actually answers the 'headline' question which is why I'm here – zzapper Mar 01 '19 at 15:41
10
[0-9]+(,[0-9]+)+

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

Jimmy
  • 2,191
  • 6
  • 25
  • 45
1

You can try with this Regex:

^[1-8](,[1-8])+$
Santosh Panda
  • 7,235
  • 8
  • 43
  • 56
1

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')]
kiran beethoju
  • 141
  • 1
  • 4
0

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])*$
quux00
  • 13,679
  • 10
  • 57
  • 69