Reputation: 3278
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
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
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