tags:

views:

690

answers:

5

whats the regex to validate a comma delimited list like this one 12365, 45236, 458, 1, 99996332, ...... thanks

+3  A: 
(?<=,|^)([^,]*)(,\1)+(?=,|$)

Reference.

also..

,(?!(?<=(?:^|,)\s*"(?:[^"]|""|\\")*,)(?:[^"]|""|\\")*"\s*(?:,|$))

Reference.

madcolor
+1  A: 

You might want to specify language just to be safe, but

(\d+, ?)+(\d+)?

ought to work

David Berger
This solution fails for a list containing only 1 element. See my solution below.
Asaph
+1  A: 

It depends a bit on your exact requirements. I'm assuming: all numbers, any length, numbers cannot have leading zeros nor contain commas or decimal points. individual numbers always separated by a comma then a space, and the last number does NOT have a comma and space after it. Any of these being wrong would simplify the solution.

([1-9][0-9]*,[ ])*[1-9][0-9]*

Here's how I built that mentally:

[0-9]  any digit.
[1-9][0-9]*  leading non-zero digit followed by any number of digits
[1-9][0-9]*, as above, followed by a comma
[1-9][0-9]*[ ]  as above, followed by a space
([1-9][0-9]*[ ])*  as above, repeated 0 or more times
([1-9][0-9]*[ ])*[1-9][0-9]*  as above, with a final number that doesn't have a comma.
mcherm
thanks for the quick tutorial
everLearningStudent
A: 
/^\d+(?:, ?\d+)*$/
w35l3y
+2  A: 

The accepted solution will not work for a list containing only 1 element. Also, it will match trailing comma and whitespace. I suggest it be modified to:

(\d+)(,\s*\d+)*

Asaph
you are right, i had to strip a first character before I could use the regex, thanks all for helping out
everLearningStudent
this seems to be working only up to the first comma...
ondrobaco
@ondrobaco: You're probably only inspecting the first match group. The next match group will contain the rest of the list.
Asaph