ojhawkins
ojhawkins

Reputation: 3278

Regex to match comma separated list with no comma on the end

I need a .Net (C#) Regex to match a comma separated list of numbers that will not match if there is a comma as the last character

123,123,123,123 true - correct match
123,123,123,123, false - comma on end 
123,123,123,,123 false - double comma
,123,123,123,123 false - comma at start
"" false - empty string

123 true - single value

I have found this Regex but matches when there is a comma on the end ^([0-9]+,?)+$

What would be a Regex pattern that would fit this pattern?

EDIT: Added 1 example for clarity the correct answer works for 123

Upvotes: 6

Views: 15095

Answers (3)

unlimit
unlimit

Reputation: 3752

Try this:

//This regex was provided before the question was edited to say that
//a single number is valid.
^((\d+\s*,\s*)+(\s*)(\d+))$

//In case a single number is valid
^(\d+)(\s*)(,\s*\d+)*$ 

Here are the test results

 123,123,123,123    match
 123,123,123,123,   no match 
 123,123,123,,123   no match
 ,123,123,123,123   no match
 ""                 no match (empty string)
 123                no match for the first regex, match for the second one

See Regex doesn't give me expected result

Edit: Modified the regex to include the last case of a single number without any comma.

Upvotes: 3

RAJESH KUMAR
RAJESH KUMAR

Reputation: 517

Please Try this

No postfix/prefix commas: [0-9]+(,[0-9]+)*

No prefix (optional postfix): [0-9]+(,[0-9]+)*,?

No postfix (optional prefix): ,?[0-9]+(,[0-9])*

Optional postfix and prefix: ,?[0-9]+(,[0-9]+)*,?

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 148980

Try using this pattern:

^([0-9]+,)*[0-9]+$

You can test it here.

Upvotes: 14

Related Questions