tags:

views:

730

answers:

1

I'm trying to validate user input, which is just comma separated numbers. I'd like to do this with RegEx, but can't come up with the right expression.

It should validate the following strings (and larger):

1
12
123
1,234
12,345
123,456

and invalidate the following strings (and crazier):

1,1
1,12
12,1
12,12
123,1
123,1

Any help would be greatly appreciated.

Here's what I've tried so far (EDIT: which don't work), along with several variants ->

^(((\d{1,3},)*\d{3})|(\d{1,3}))$
^(\d{1,3}[,])*\d{3}|\d{1,3}$
+8  A: 

How about this:

^\d{1,3}([,]\d{3})*$

Basically you can have 1-3 digits comma free. After that, you need a comma. If you've got a comma, it must be followed by 3 more digits. That comma-3-digit sequence can appear any number of times.

EDIT: As Andrew Hare observed, you don't care about what was found inside the parentheses beyond the fact that it matched, so you can use a non-capturing group instead by placing ?: after the opening parenthesis:

^\d{1,3}(?:[,]\d{3})*$
Adam Bellaire
+1 Nicely done. My only criticism: since this regular expression is for validation only you should change that capture group to be a non-capture group.
Andrew Hare
Good point, but it has always bothered me that making a group non-capture makes the regex more ugly.
Adam Bellaire
looking at the original regex it looks lit a string like 12,1,123 is legal ((\d{1,3},)*\d{3}) which the above does not satisfy
Rune FS
@Rune FS: The OP states that the original regex is not working as he intends. This is why he provided test input.
Adam Bellaire
Will this validate "123,456123,456" ?
Faiz
@Faiz: That string is not valid, and this regex will show that. Go ahead and try it. :)
Adam Bellaire