简体   繁体   中英

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

Try using this pattern:

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

You can test it here .

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.

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]+)*,?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM